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 "time_support.h"
46 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
48 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv);
49 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv);
52 extern struct target_type arm7tdmi_target;
53 extern struct target_type arm720t_target;
54 extern struct target_type arm9tdmi_target;
55 extern struct target_type arm920t_target;
56 extern struct target_type arm966e_target;
57 extern struct target_type arm926ejs_target;
58 extern struct target_type fa526_target;
59 extern struct target_type feroceon_target;
60 extern struct target_type dragonite_target;
61 extern struct target_type xscale_target;
62 extern struct target_type cortexm3_target;
63 extern struct target_type cortexa8_target;
64 extern struct target_type arm11_target;
65 extern struct target_type mips_m4k_target;
66 extern struct target_type avr_target;
68 struct target_type *target_types[] =
88 struct target *all_targets = NULL;
89 struct target_event_callback *target_event_callbacks = NULL;
90 struct target_timer_callback *target_timer_callbacks = NULL;
92 const Jim_Nvp nvp_assert[] = {
93 { .name = "assert", NVP_ASSERT },
94 { .name = "deassert", NVP_DEASSERT },
95 { .name = "T", NVP_ASSERT },
96 { .name = "F", NVP_DEASSERT },
97 { .name = "t", NVP_ASSERT },
98 { .name = "f", NVP_DEASSERT },
99 { .name = NULL, .value = -1 }
102 const Jim_Nvp nvp_error_target[] = {
103 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
104 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
105 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
106 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
107 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
108 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
109 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
110 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
111 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
112 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
113 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
114 { .value = -1, .name = NULL }
117 const char *target_strerror_safe(int err)
121 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
122 if (n->name == NULL) {
129 static const Jim_Nvp nvp_target_event[] = {
130 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
131 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
133 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
134 { .value = TARGET_EVENT_HALTED, .name = "halted" },
135 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
136 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
137 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
139 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
140 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
142 /* historical name */
144 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
146 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
147 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
148 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
149 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
150 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
151 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
152 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
153 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
154 { .value = TARGET_EVENT_RESET_INIT , .name = "reset-init" },
155 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
157 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
158 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
160 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
161 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
163 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
164 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
166 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
167 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
169 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
170 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
172 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
173 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
174 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
176 { .name = NULL, .value = -1 }
179 const Jim_Nvp nvp_target_state[] = {
180 { .name = "unknown", .value = TARGET_UNKNOWN },
181 { .name = "running", .value = TARGET_RUNNING },
182 { .name = "halted", .value = TARGET_HALTED },
183 { .name = "reset", .value = TARGET_RESET },
184 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
185 { .name = NULL, .value = -1 },
188 const Jim_Nvp nvp_target_debug_reason [] = {
189 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
190 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
191 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
192 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
193 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
194 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
195 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
196 { .name = NULL, .value = -1 },
199 const Jim_Nvp nvp_target_endian[] = {
200 { .name = "big", .value = TARGET_BIG_ENDIAN },
201 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
202 { .name = "be", .value = TARGET_BIG_ENDIAN },
203 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
204 { .name = NULL, .value = -1 },
207 const Jim_Nvp nvp_reset_modes[] = {
208 { .name = "unknown", .value = RESET_UNKNOWN },
209 { .name = "run" , .value = RESET_RUN },
210 { .name = "halt" , .value = RESET_HALT },
211 { .name = "init" , .value = RESET_INIT },
212 { .name = NULL , .value = -1 },
216 target_state_name( struct target *t )
219 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
221 LOG_ERROR("Invalid target state: %d", (int)(t->state));
222 cp = "(*BUG*unknown*BUG*)";
227 /* determine the number of the new target */
228 static int new_target_number(void)
233 /* number is 0 based */
237 if (x < t->target_number) {
238 x = t->target_number;
245 /* read a uint32_t from a buffer in target memory endianness */
246 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
248 if (target->endianness == TARGET_LITTLE_ENDIAN)
249 return le_to_h_u32(buffer);
251 return be_to_h_u32(buffer);
254 /* read a uint16_t from a buffer in target memory endianness */
255 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
257 if (target->endianness == TARGET_LITTLE_ENDIAN)
258 return le_to_h_u16(buffer);
260 return be_to_h_u16(buffer);
263 /* read a uint8_t from a buffer in target memory endianness */
264 uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
266 return *buffer & 0x0ff;
269 /* write a uint32_t to a buffer in target memory endianness */
270 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
272 if (target->endianness == TARGET_LITTLE_ENDIAN)
273 h_u32_to_le(buffer, value);
275 h_u32_to_be(buffer, value);
278 /* write a uint16_t to a buffer in target memory endianness */
279 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
281 if (target->endianness == TARGET_LITTLE_ENDIAN)
282 h_u16_to_le(buffer, value);
284 h_u16_to_be(buffer, value);
287 /* write a uint8_t to a buffer in target memory endianness */
288 void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
293 /* return a pointer to a configured target; id is name or number */
294 struct target *get_target(const char *id)
296 struct target *target;
298 /* try as tcltarget name */
299 for (target = all_targets; target; target = target->next) {
300 if (target->cmd_name == NULL)
302 if (strcmp(id, target->cmd_name) == 0)
306 /* It's OK to remove this fallback sometime after August 2010 or so */
308 /* no match, try as number */
310 if (parse_uint(id, &num) != ERROR_OK)
313 for (target = all_targets; target; target = target->next) {
314 if (target->target_number == (int)num) {
315 LOG_WARNING("use '%s' as target identifier, not '%u'",
316 target->cmd_name, num);
324 /* returns a pointer to the n-th configured target */
325 static struct target *get_target_by_num(int num)
327 struct target *target = all_targets;
330 if (target->target_number == num) {
333 target = target->next;
339 struct target* get_current_target(struct command_context *cmd_ctx)
341 struct target *target = get_target_by_num(cmd_ctx->current_target);
345 LOG_ERROR("BUG: current_target out of bounds");
352 int target_poll(struct target *target)
356 /* We can't poll until after examine */
357 if (!target_was_examined(target))
359 /* Fail silently lest we pollute the log */
363 retval = target->type->poll(target);
364 if (retval != ERROR_OK)
367 if (target->halt_issued)
369 if (target->state == TARGET_HALTED)
371 target->halt_issued = false;
374 long long t = timeval_ms() - target->halt_issued_time;
377 target->halt_issued = false;
378 LOG_INFO("Halt timed out, wake up GDB.");
379 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
387 int target_halt(struct target *target)
390 /* We can't poll until after examine */
391 if (!target_was_examined(target))
393 LOG_ERROR("Target not examined yet");
397 retval = target->type->halt(target);
398 if (retval != ERROR_OK)
401 target->halt_issued = true;
402 target->halt_issued_time = timeval_ms();
407 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
411 /* We can't poll until after examine */
412 if (!target_was_examined(target))
414 LOG_ERROR("Target not examined yet");
418 /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
419 * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
422 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
428 int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
433 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
434 if (n->name == NULL) {
435 LOG_ERROR("invalid reset mode");
439 /* disable polling during reset to make reset event scripts
440 * more predictable, i.e. dr/irscan & pathmove in events will
441 * not have JTAG operations injected into the middle of a sequence.
443 bool save_poll = jtag_poll_get_enabled();
445 jtag_poll_set_enabled(false);
447 sprintf(buf, "ocd_process_reset %s", n->name);
448 retval = Jim_Eval(interp, buf);
450 jtag_poll_set_enabled(save_poll);
452 if (retval != JIM_OK) {
453 Jim_PrintErrorMessage(interp);
457 /* We want any events to be processed before the prompt */
458 retval = target_call_timer_callbacks_now();
463 static int identity_virt2phys(struct target *target,
464 uint32_t virtual, uint32_t *physical)
470 static int no_mmu(struct target *target, int *enabled)
476 static int default_examine(struct target *target)
478 target_set_examined(target);
482 int target_examine_one(struct target *target)
484 return target->type->examine(target);
487 static int jtag_enable_callback(enum jtag_event event, void *priv)
489 struct target *target = priv;
491 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
494 jtag_unregister_event_callback(jtag_enable_callback, target);
495 return target_examine_one(target);
499 /* Targets that correctly implement init + examine, i.e.
500 * no communication with target during init:
504 int target_examine(void)
506 int retval = ERROR_OK;
507 struct target *target;
509 for (target = all_targets; target; target = target->next)
511 /* defer examination, but don't skip it */
512 if (!target->tap->enabled) {
513 jtag_register_event_callback(jtag_enable_callback,
517 if ((retval = target_examine_one(target)) != ERROR_OK)
522 const char *target_get_name(struct target *target)
524 return target->type->name;
527 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
529 if (!target_was_examined(target))
531 LOG_ERROR("Target not examined yet");
534 return target->type->write_memory_imp(target, address, size, count, buffer);
537 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
539 if (!target_was_examined(target))
541 LOG_ERROR("Target not examined yet");
544 return target->type->read_memory_imp(target, address, size, count, buffer);
547 static int target_soft_reset_halt_imp(struct target *target)
549 if (!target_was_examined(target))
551 LOG_ERROR("Target not examined yet");
554 if (!target->type->soft_reset_halt_imp) {
555 LOG_ERROR("Target %s does not support soft_reset_halt",
559 return target->type->soft_reset_halt_imp(target);
562 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)
564 if (!target_was_examined(target))
566 LOG_ERROR("Target not examined yet");
569 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);
572 int target_read_memory(struct target *target,
573 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
575 return target->type->read_memory(target, address, size, count, buffer);
578 int target_read_phys_memory(struct target *target,
579 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
581 return target->type->read_phys_memory(target, address, size, count, buffer);
584 int target_write_memory(struct target *target,
585 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
587 return target->type->write_memory(target, address, size, count, buffer);
590 int target_write_phys_memory(struct target *target,
591 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
593 return target->type->write_phys_memory(target, address, size, count, buffer);
596 int target_bulk_write_memory(struct target *target,
597 uint32_t address, uint32_t count, uint8_t *buffer)
599 return target->type->bulk_write_memory(target, address, count, buffer);
602 int target_add_breakpoint(struct target *target,
603 struct breakpoint *breakpoint)
605 return target->type->add_breakpoint(target, breakpoint);
607 int target_remove_breakpoint(struct target *target,
608 struct breakpoint *breakpoint)
610 return target->type->remove_breakpoint(target, breakpoint);
613 int target_add_watchpoint(struct target *target,
614 struct watchpoint *watchpoint)
616 return target->type->add_watchpoint(target, watchpoint);
618 int target_remove_watchpoint(struct target *target,
619 struct watchpoint *watchpoint)
621 return target->type->remove_watchpoint(target, watchpoint);
624 int target_get_gdb_reg_list(struct target *target,
625 struct reg **reg_list[], int *reg_list_size)
627 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
629 int target_step(struct target *target,
630 int current, uint32_t address, int handle_breakpoints)
632 return target->type->step(target, current, address, handle_breakpoints);
636 int target_run_algorithm(struct target *target,
637 int num_mem_params, struct mem_param *mem_params,
638 int num_reg_params, struct reg_param *reg_param,
639 uint32_t entry_point, uint32_t exit_point,
640 int timeout_ms, void *arch_info)
642 return target->type->run_algorithm(target,
643 num_mem_params, mem_params, num_reg_params, reg_param,
644 entry_point, exit_point, timeout_ms, arch_info);
648 * Reset the @c examined flag for the given target.
649 * Pure paranoia -- targets are zeroed on allocation.
651 static void target_reset_examined(struct target *target)
653 target->examined = false;
658 static int default_mrc(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
660 LOG_ERROR("Not implemented: %s", __func__);
664 static int default_mcr(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
666 LOG_ERROR("Not implemented: %s", __func__);
670 static int arm_cp_check(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm)
673 if (!target_was_examined(target))
675 LOG_ERROR("Target not examined yet");
679 if ((cpnum <0) || (cpnum > 15))
681 LOG_ERROR("Illegal co-processor %d", cpnum);
687 LOG_ERROR("Illegal op1");
693 LOG_ERROR("Illegal op2");
699 LOG_ERROR("Illegal CRn");
705 LOG_ERROR("Illegal CRm");
712 int target_mrc(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
716 retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
717 if (retval != ERROR_OK)
720 return target->type->mrc(target, cpnum, op1, op2, CRn, CRm, value);
723 int target_mcr(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
727 retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
728 if (retval != ERROR_OK)
731 return target->type->mcr(target, cpnum, op1, op2, CRn, CRm, value);
735 err_read_phys_memory(struct target *target, uint32_t address,
736 uint32_t size, uint32_t count, uint8_t *buffer)
738 LOG_ERROR("Not implemented: %s", __func__);
743 err_write_phys_memory(struct target *target, uint32_t address,
744 uint32_t size, uint32_t count, uint8_t *buffer)
746 LOG_ERROR("Not implemented: %s", __func__);
750 int target_init(struct command_context *cmd_ctx)
752 struct target *target;
755 for (target = all_targets; target; target = target->next) {
756 struct target_type *type = target->type;
758 target_reset_examined(target);
759 if (target->type->examine == NULL)
761 target->type->examine = default_examine;
764 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
766 LOG_ERROR("target '%s' init failed", target_get_name(target));
771 * @todo MCR/MRC are ARM-specific; don't require them in
772 * all targets, or for ARMs without coprocessors.
774 if (target->type->mcr == NULL)
776 target->type->mcr = default_mcr;
779 /* FIX! multiple targets will generally register global commands
780 * multiple times. Only register this one if *one* of the
781 * targets need the command. Hmm... make it a command on the
782 * Jim Tcl target object?
784 register_jim(cmd_ctx, "mcr", jim_mcrmrc, "write coprocessor <cpnum> <op1> <op2> <CRn> <CRm> <value>");
787 if (target->type->mrc == NULL)
789 target->type->mrc = default_mrc;
792 register_jim(cmd_ctx, "mrc", jim_mcrmrc, "read coprocessor <cpnum> <op1> <op2> <CRn> <CRm>");
797 * @todo get rid of those *memory_imp() methods, now that all
798 * callers are using target_*_memory() accessors ... and make
799 * sure the "physical" paths handle the same issues.
802 /* a non-invasive way(in terms of patches) to add some code that
803 * runs before the type->write/read_memory implementation
805 target->type->write_memory_imp = target->type->write_memory;
806 target->type->write_memory = target_write_memory_imp;
807 target->type->read_memory_imp = target->type->read_memory;
808 target->type->read_memory = target_read_memory_imp;
809 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
810 target->type->soft_reset_halt = target_soft_reset_halt_imp;
811 target->type->run_algorithm_imp = target->type->run_algorithm;
812 target->type->run_algorithm = target_run_algorithm_imp;
814 /* Sanity-check MMU support ... stub in what we must, to help
815 * implement it in stages, but warn if we need to do so.
818 if (type->write_phys_memory == NULL) {
819 LOG_ERROR("type '%s' is missing %s",
821 "write_phys_memory");
822 type->write_phys_memory = err_write_phys_memory;
824 if (type->read_phys_memory == NULL) {
825 LOG_ERROR("type '%s' is missing %s",
828 type->read_phys_memory = err_read_phys_memory;
830 if (type->virt2phys == NULL) {
831 LOG_ERROR("type '%s' is missing %s",
834 type->virt2phys = identity_virt2phys;
837 /* Make sure no-MMU targets all behave the same: make no
838 * distinction between physical and virtual addresses, and
839 * ensure that virt2phys() is always an identity mapping.
842 if (type->write_phys_memory
843 || type->read_phys_memory
845 LOG_WARNING("type '%s' has broken MMU hooks",
849 type->write_phys_memory = type->write_memory;
850 type->read_phys_memory = type->read_memory;
851 type->virt2phys = identity_virt2phys;
857 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
859 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
866 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
868 struct target_event_callback **callbacks_p = &target_event_callbacks;
870 if (callback == NULL)
872 return ERROR_INVALID_ARGUMENTS;
877 while ((*callbacks_p)->next)
878 callbacks_p = &((*callbacks_p)->next);
879 callbacks_p = &((*callbacks_p)->next);
882 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
883 (*callbacks_p)->callback = callback;
884 (*callbacks_p)->priv = priv;
885 (*callbacks_p)->next = NULL;
890 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
892 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
895 if (callback == NULL)
897 return ERROR_INVALID_ARGUMENTS;
902 while ((*callbacks_p)->next)
903 callbacks_p = &((*callbacks_p)->next);
904 callbacks_p = &((*callbacks_p)->next);
907 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
908 (*callbacks_p)->callback = callback;
909 (*callbacks_p)->periodic = periodic;
910 (*callbacks_p)->time_ms = time_ms;
912 gettimeofday(&now, NULL);
913 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
914 time_ms -= (time_ms % 1000);
915 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
916 if ((*callbacks_p)->when.tv_usec > 1000000)
918 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
919 (*callbacks_p)->when.tv_sec += 1;
922 (*callbacks_p)->priv = priv;
923 (*callbacks_p)->next = NULL;
928 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
930 struct target_event_callback **p = &target_event_callbacks;
931 struct target_event_callback *c = target_event_callbacks;
933 if (callback == NULL)
935 return ERROR_INVALID_ARGUMENTS;
940 struct target_event_callback *next = c->next;
941 if ((c->callback == callback) && (c->priv == priv))
955 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
957 struct target_timer_callback **p = &target_timer_callbacks;
958 struct target_timer_callback *c = target_timer_callbacks;
960 if (callback == NULL)
962 return ERROR_INVALID_ARGUMENTS;
967 struct target_timer_callback *next = c->next;
968 if ((c->callback == callback) && (c->priv == priv))
982 int target_call_event_callbacks(struct target *target, enum target_event event)
984 struct target_event_callback *callback = target_event_callbacks;
985 struct target_event_callback *next_callback;
987 if (event == TARGET_EVENT_HALTED)
989 /* execute early halted first */
990 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
993 LOG_DEBUG("target event %i (%s)",
995 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
997 target_handle_event(target, event);
1001 next_callback = callback->next;
1002 callback->callback(target, event, callback->priv);
1003 callback = next_callback;
1009 static int target_timer_callback_periodic_restart(
1010 struct target_timer_callback *cb, struct timeval *now)
1012 int time_ms = cb->time_ms;
1013 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1014 time_ms -= (time_ms % 1000);
1015 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1016 if (cb->when.tv_usec > 1000000)
1018 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1019 cb->when.tv_sec += 1;
1024 static int target_call_timer_callback(struct target_timer_callback *cb,
1025 struct timeval *now)
1027 cb->callback(cb->priv);
1030 return target_timer_callback_periodic_restart(cb, now);
1032 return target_unregister_timer_callback(cb->callback, cb->priv);
1035 static int target_call_timer_callbacks_check_time(int checktime)
1040 gettimeofday(&now, NULL);
1042 struct target_timer_callback *callback = target_timer_callbacks;
1045 // cleaning up may unregister and free this callback
1046 struct target_timer_callback *next_callback = callback->next;
1048 bool call_it = callback->callback &&
1049 ((!checktime && callback->periodic) ||
1050 now.tv_sec > callback->when.tv_sec ||
1051 (now.tv_sec == callback->when.tv_sec &&
1052 now.tv_usec >= callback->when.tv_usec));
1056 int retval = target_call_timer_callback(callback, &now);
1057 if (retval != ERROR_OK)
1061 callback = next_callback;
1067 int target_call_timer_callbacks(void)
1069 return target_call_timer_callbacks_check_time(1);
1072 /* invoke periodic callbacks immediately */
1073 int target_call_timer_callbacks_now(void)
1075 return target_call_timer_callbacks_check_time(0);
1078 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1080 struct working_area *c = target->working_areas;
1081 struct working_area *new_wa = NULL;
1083 /* Reevaluate working area address based on MMU state*/
1084 if (target->working_areas == NULL)
1089 retval = target->type->mmu(target, &enabled);
1090 if (retval != ERROR_OK)
1096 if (target->working_area_phys_spec) {
1097 LOG_DEBUG("MMU disabled, using physical "
1098 "address for working memory 0x%08x",
1099 (unsigned)target->working_area_phys);
1100 target->working_area = target->working_area_phys;
1102 LOG_ERROR("No working memory available. "
1103 "Specify -work-area-phys to target.");
1104 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1107 if (target->working_area_virt_spec) {
1108 LOG_DEBUG("MMU enabled, using virtual "
1109 "address for working memory 0x%08x",
1110 (unsigned)target->working_area_virt);
1111 target->working_area = target->working_area_virt;
1113 LOG_ERROR("No working memory available. "
1114 "Specify -work-area-virt to target.");
1115 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1120 /* only allocate multiples of 4 byte */
1123 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1124 size = (size + 3) & (~3);
1127 /* see if there's already a matching working area */
1130 if ((c->free) && (c->size == size))
1138 /* if not, allocate a new one */
1141 struct working_area **p = &target->working_areas;
1142 uint32_t first_free = target->working_area;
1143 uint32_t free_size = target->working_area_size;
1145 c = target->working_areas;
1148 first_free += c->size;
1149 free_size -= c->size;
1154 if (free_size < size)
1156 LOG_WARNING("not enough working area available(requested %u, free %u)",
1157 (unsigned)(size), (unsigned)(free_size));
1158 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1161 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1163 new_wa = malloc(sizeof(struct working_area));
1164 new_wa->next = NULL;
1165 new_wa->size = size;
1166 new_wa->address = first_free;
1168 if (target->backup_working_area)
1171 new_wa->backup = malloc(new_wa->size);
1172 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1174 free(new_wa->backup);
1181 new_wa->backup = NULL;
1184 /* put new entry in list */
1188 /* mark as used, and return the new (reused) area */
1193 new_wa->user = area;
1198 int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1203 if (restore && target->backup_working_area)
1206 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1212 /* mark user pointer invalid */
1219 int target_free_working_area(struct target *target, struct working_area *area)
1221 return target_free_working_area_restore(target, area, 1);
1224 /* free resources and restore memory, if restoring memory fails,
1225 * free up resources anyway
1227 void target_free_all_working_areas_restore(struct target *target, int restore)
1229 struct working_area *c = target->working_areas;
1233 struct working_area *next = c->next;
1234 target_free_working_area_restore(target, c, restore);
1244 target->working_areas = NULL;
1247 void target_free_all_working_areas(struct target *target)
1249 target_free_all_working_areas_restore(target, 1);
1252 int target_arch_state(struct target *target)
1257 LOG_USER("No target has been configured");
1261 LOG_USER("target state: %s", target_state_name( target ));
1263 if (target->state != TARGET_HALTED)
1266 retval = target->type->arch_state(target);
1270 /* Single aligned words are guaranteed to use 16 or 32 bit access
1271 * mode respectively, otherwise data is handled as quickly as
1274 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1277 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1278 (int)size, (unsigned)address);
1280 if (!target_was_examined(target))
1282 LOG_ERROR("Target not examined yet");
1290 if ((address + size - 1) < address)
1292 /* GDB can request this when e.g. PC is 0xfffffffc*/
1293 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1299 if (((address % 2) == 0) && (size == 2))
1301 return target_write_memory(target, address, 2, 1, buffer);
1304 /* handle unaligned head bytes */
1307 uint32_t unaligned = 4 - (address % 4);
1309 if (unaligned > size)
1312 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1315 buffer += unaligned;
1316 address += unaligned;
1320 /* handle aligned words */
1323 int aligned = size - (size % 4);
1325 /* use bulk writes above a certain limit. This may have to be changed */
1328 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1333 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1342 /* handle tail writes of less than 4 bytes */
1345 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1352 /* Single aligned words are guaranteed to use 16 or 32 bit access
1353 * mode respectively, otherwise data is handled as quickly as
1356 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1359 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1360 (int)size, (unsigned)address);
1362 if (!target_was_examined(target))
1364 LOG_ERROR("Target not examined yet");
1372 if ((address + size - 1) < address)
1374 /* GDB can request this when e.g. PC is 0xfffffffc*/
1375 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1381 if (((address % 2) == 0) && (size == 2))
1383 return target_read_memory(target, address, 2, 1, buffer);
1386 /* handle unaligned head bytes */
1389 uint32_t unaligned = 4 - (address % 4);
1391 if (unaligned > size)
1394 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1397 buffer += unaligned;
1398 address += unaligned;
1402 /* handle aligned words */
1405 int aligned = size - (size % 4);
1407 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1415 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1418 int aligned = size - (size%2);
1419 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1420 if (retval != ERROR_OK)
1427 /* handle tail writes of less than 4 bytes */
1430 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1437 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1442 uint32_t checksum = 0;
1443 if (!target_was_examined(target))
1445 LOG_ERROR("Target not examined yet");
1449 if ((retval = target->type->checksum_memory(target, address,
1450 size, &checksum)) != ERROR_OK)
1452 buffer = malloc(size);
1455 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1456 return ERROR_INVALID_ARGUMENTS;
1458 retval = target_read_buffer(target, address, size, buffer);
1459 if (retval != ERROR_OK)
1465 /* convert to target endianess */
1466 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1468 uint32_t target_data;
1469 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1470 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1473 retval = image_calculate_checksum(buffer, size, &checksum);
1482 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1485 if (!target_was_examined(target))
1487 LOG_ERROR("Target not examined yet");
1491 if (target->type->blank_check_memory == 0)
1492 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1494 retval = target->type->blank_check_memory(target, address, size, blank);
1499 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1501 uint8_t value_buf[4];
1502 if (!target_was_examined(target))
1504 LOG_ERROR("Target not examined yet");
1508 int retval = target_read_memory(target, address, 4, 1, value_buf);
1510 if (retval == ERROR_OK)
1512 *value = target_buffer_get_u32(target, value_buf);
1513 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1520 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1527 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1529 uint8_t value_buf[2];
1530 if (!target_was_examined(target))
1532 LOG_ERROR("Target not examined yet");
1536 int retval = target_read_memory(target, address, 2, 1, value_buf);
1538 if (retval == ERROR_OK)
1540 *value = target_buffer_get_u16(target, value_buf);
1541 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1548 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1555 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1557 int retval = target_read_memory(target, address, 1, 1, value);
1558 if (!target_was_examined(target))
1560 LOG_ERROR("Target not examined yet");
1564 if (retval == ERROR_OK)
1566 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1573 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1580 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1583 uint8_t value_buf[4];
1584 if (!target_was_examined(target))
1586 LOG_ERROR("Target not examined yet");
1590 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1594 target_buffer_set_u32(target, value_buf, value);
1595 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1597 LOG_DEBUG("failed: %i", retval);
1603 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1606 uint8_t value_buf[2];
1607 if (!target_was_examined(target))
1609 LOG_ERROR("Target not examined yet");
1613 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1617 target_buffer_set_u16(target, value_buf, value);
1618 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1620 LOG_DEBUG("failed: %i", retval);
1626 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1629 if (!target_was_examined(target))
1631 LOG_ERROR("Target not examined yet");
1635 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1638 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1640 LOG_DEBUG("failed: %i", retval);
1646 COMMAND_HANDLER(handle_targets_command)
1648 struct target *target = all_targets;
1652 target = get_target(args[0]);
1653 if (target == NULL) {
1654 command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1657 if (!target->tap->enabled) {
1658 command_print(cmd_ctx,"Target: TAP %s is disabled, "
1659 "can't be the current target\n",
1660 target->tap->dotted_name);
1664 cmd_ctx->current_target = target->target_number;
1669 target = all_targets;
1670 command_print(cmd_ctx, " TargetName Type Endian TapName State ");
1671 command_print(cmd_ctx, "-- ------------------ ---------- ------ ------------------ ------------");
1677 if (target->tap->enabled)
1678 state = target_state_name( target );
1680 state = "tap-disabled";
1682 if (cmd_ctx->current_target == target->target_number)
1685 /* keep columns lined up to match the headers above */
1686 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1687 target->target_number,
1690 target_get_name(target),
1691 Jim_Nvp_value2name_simple(nvp_target_endian,
1692 target->endianness)->name,
1693 target->tap->dotted_name,
1695 target = target->next;
1701 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1703 static int powerDropout;
1704 static int srstAsserted;
1706 static int runPowerRestore;
1707 static int runPowerDropout;
1708 static int runSrstAsserted;
1709 static int runSrstDeasserted;
1711 static int sense_handler(void)
1713 static int prevSrstAsserted = 0;
1714 static int prevPowerdropout = 0;
1717 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1721 powerRestored = prevPowerdropout && !powerDropout;
1724 runPowerRestore = 1;
1727 long long current = timeval_ms();
1728 static long long lastPower = 0;
1729 int waitMore = lastPower + 2000 > current;
1730 if (powerDropout && !waitMore)
1732 runPowerDropout = 1;
1733 lastPower = current;
1736 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1740 srstDeasserted = prevSrstAsserted && !srstAsserted;
1742 static long long lastSrst = 0;
1743 waitMore = lastSrst + 2000 > current;
1744 if (srstDeasserted && !waitMore)
1746 runSrstDeasserted = 1;
1750 if (!prevSrstAsserted && srstAsserted)
1752 runSrstAsserted = 1;
1755 prevSrstAsserted = srstAsserted;
1756 prevPowerdropout = powerDropout;
1758 if (srstDeasserted || powerRestored)
1760 /* Other than logging the event we can't do anything here.
1761 * Issuing a reset is a particularly bad idea as we might
1762 * be inside a reset already.
1769 static void target_call_event_callbacks_all(enum target_event e) {
1770 struct target *target;
1771 target = all_targets;
1773 target_call_event_callbacks(target, e);
1774 target = target->next;
1778 /* process target state changes */
1779 int handle_target(void *priv)
1781 int retval = ERROR_OK;
1783 /* we do not want to recurse here... */
1784 static int recursive = 0;
1789 /* danger! running these procedures can trigger srst assertions and power dropouts.
1790 * We need to avoid an infinite loop/recursion here and we do that by
1791 * clearing the flags after running these events.
1793 int did_something = 0;
1794 if (runSrstAsserted)
1796 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1797 Jim_Eval(interp, "srst_asserted");
1800 if (runSrstDeasserted)
1802 Jim_Eval(interp, "srst_deasserted");
1805 if (runPowerDropout)
1807 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1808 Jim_Eval(interp, "power_dropout");
1811 if (runPowerRestore)
1813 Jim_Eval(interp, "power_restore");
1819 /* clear detect flags */
1823 /* clear action flags */
1825 runSrstAsserted = 0;
1826 runSrstDeasserted = 0;
1827 runPowerRestore = 0;
1828 runPowerDropout = 0;
1833 /* Poll targets for state changes unless that's globally disabled.
1834 * Skip targets that are currently disabled.
1836 for (struct target *target = all_targets;
1837 is_jtag_poll_safe() && target;
1838 target = target->next)
1840 if (!target->tap->enabled)
1843 /* only poll target if we've got power and srst isn't asserted */
1844 if (!powerDropout && !srstAsserted)
1846 /* polling may fail silently until the target has been examined */
1847 if ((retval = target_poll(target)) != ERROR_OK)
1849 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1858 COMMAND_HANDLER(handle_reg_command)
1860 struct target *target;
1861 struct reg *reg = NULL;
1867 target = get_current_target(cmd_ctx);
1869 /* list all available registers for the current target */
1872 struct reg_cache *cache = target->reg_cache;
1879 command_print(cmd_ctx, "===== %s", cache->name);
1881 for (i = 0, reg = cache->reg_list;
1882 i < cache->num_regs;
1883 i++, reg++, count++)
1885 /* only print cached values if they are valid */
1887 value = buf_to_str(reg->value,
1889 command_print(cmd_ctx,
1890 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1898 command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1903 cache = cache->next;
1909 /* access a single register by its ordinal number */
1910 if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1913 COMMAND_PARSE_NUMBER(uint, args[0], num);
1915 struct reg_cache *cache = target->reg_cache;
1920 for (i = 0; i < cache->num_regs; i++)
1922 if (count++ == (int)num)
1924 reg = &cache->reg_list[i];
1930 cache = cache->next;
1935 command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1938 } else /* access a single register by its name */
1940 reg = register_get_by_name(target->reg_cache, args[0], 1);
1944 command_print(cmd_ctx, "register %s not found in current target", args[0]);
1949 /* display a register */
1950 if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1952 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1955 if (reg->valid == 0)
1957 struct reg_arch_type *arch_type = register_get_arch_type(reg->arch_type);
1958 arch_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(CEIL(reg->size, 8));
1970 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1972 struct reg_arch_type *arch_type = register_get_arch_type(reg->arch_type);
1973 arch_type->set(reg, buf);
1975 value = buf_to_str(reg->value, reg->size, 16);
1976 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1984 command_print(cmd_ctx, "usage: reg <#|name> [value]");
1989 COMMAND_HANDLER(handle_poll_command)
1991 int retval = ERROR_OK;
1992 struct target *target = get_current_target(cmd_ctx);
1996 command_print(cmd_ctx, "background polling: %s",
1997 jtag_poll_get_enabled() ? "on" : "off");
1998 command_print(cmd_ctx, "TAP: %s (%s)",
1999 target->tap->dotted_name,
2000 target->tap->enabled ? "enabled" : "disabled");
2001 if (!target->tap->enabled)
2003 if ((retval = target_poll(target)) != ERROR_OK)
2005 if ((retval = target_arch_state(target)) != ERROR_OK)
2011 if (strcmp(args[0], "on") == 0)
2013 jtag_poll_set_enabled(true);
2015 else if (strcmp(args[0], "off") == 0)
2017 jtag_poll_set_enabled(false);
2021 command_print(cmd_ctx, "arg is \"on\" or \"off\"");
2025 return ERROR_COMMAND_SYNTAX_ERROR;
2031 COMMAND_HANDLER(handle_wait_halt_command)
2034 return ERROR_COMMAND_SYNTAX_ERROR;
2039 int retval = parse_uint(args[0], &ms);
2040 if (ERROR_OK != retval)
2042 command_print(cmd_ctx, "usage: %s [seconds]", CMD_NAME);
2043 return ERROR_COMMAND_SYNTAX_ERROR;
2045 // convert seconds (given) to milliseconds (needed)
2049 struct target *target = get_current_target(cmd_ctx);
2050 return target_wait_state(target, TARGET_HALTED, ms);
2053 /* wait for target state to change. The trick here is to have a low
2054 * latency for short waits and not to suck up all the CPU time
2057 * After 500ms, keep_alive() is invoked
2059 int target_wait_state(struct target *target, enum target_state state, int ms)
2062 long long then = 0, cur;
2067 if ((retval = target_poll(target)) != ERROR_OK)
2069 if (target->state == state)
2077 then = timeval_ms();
2078 LOG_DEBUG("waiting for target %s...",
2079 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2087 if ((cur-then) > ms)
2089 LOG_ERROR("timed out while waiting for target %s",
2090 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2098 COMMAND_HANDLER(handle_halt_command)
2102 struct target *target = get_current_target(cmd_ctx);
2103 int retval = target_halt(target);
2104 if (ERROR_OK != retval)
2110 retval = parse_uint(args[0], &wait);
2111 if (ERROR_OK != retval)
2112 return ERROR_COMMAND_SYNTAX_ERROR;
2117 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2120 COMMAND_HANDLER(handle_soft_reset_halt_command)
2122 struct target *target = get_current_target(cmd_ctx);
2124 LOG_USER("requesting target halt and executing a soft reset");
2126 target->type->soft_reset_halt(target);
2131 COMMAND_HANDLER(handle_reset_command)
2134 return ERROR_COMMAND_SYNTAX_ERROR;
2136 enum target_reset_mode reset_mode = RESET_RUN;
2140 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2141 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2142 return ERROR_COMMAND_SYNTAX_ERROR;
2144 reset_mode = n->value;
2147 /* reset *all* targets */
2148 return target_process_reset(cmd_ctx, reset_mode);
2152 COMMAND_HANDLER(handle_resume_command)
2156 return ERROR_COMMAND_SYNTAX_ERROR;
2158 struct target *target = get_current_target(cmd_ctx);
2159 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2161 /* with no args, resume from current pc, addr = 0,
2162 * with one arguments, addr = args[0],
2163 * handle breakpoints, not debugging */
2167 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2171 return target_resume(target, current, addr, 1, 0);
2174 COMMAND_HANDLER(handle_step_command)
2177 return ERROR_COMMAND_SYNTAX_ERROR;
2181 /* with no args, step from current pc, addr = 0,
2182 * with one argument addr = args[0],
2183 * handle breakpoints, debugging */
2188 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2192 struct target *target = get_current_target(cmd_ctx);
2194 return target->type->step(target, current_pc, addr, 1);
2197 static void handle_md_output(struct command_context *cmd_ctx,
2198 struct target *target, uint32_t address, unsigned size,
2199 unsigned count, const uint8_t *buffer)
2201 const unsigned line_bytecnt = 32;
2202 unsigned line_modulo = line_bytecnt / size;
2204 char output[line_bytecnt * 4 + 1];
2205 unsigned output_len = 0;
2207 const char *value_fmt;
2209 case 4: value_fmt = "%8.8x "; break;
2210 case 2: value_fmt = "%4.2x "; break;
2211 case 1: value_fmt = "%2.2x "; break;
2213 LOG_ERROR("invalid memory read size: %u", size);
2217 for (unsigned i = 0; i < count; i++)
2219 if (i % line_modulo == 0)
2221 output_len += snprintf(output + output_len,
2222 sizeof(output) - output_len,
2224 (unsigned)(address + (i*size)));
2228 const uint8_t *value_ptr = buffer + i * size;
2230 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2231 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2232 case 1: value = *value_ptr;
2234 output_len += snprintf(output + output_len,
2235 sizeof(output) - output_len,
2238 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2240 command_print(cmd_ctx, "%s", output);
2246 COMMAND_HANDLER(handle_md_command)
2249 return ERROR_COMMAND_SYNTAX_ERROR;
2252 const char *cmd_name = CMD_NAME;
2253 switch (cmd_name[6]) {
2254 case 'w': size = 4; break;
2255 case 'h': size = 2; break;
2256 case 'b': size = 1; break;
2257 default: return ERROR_COMMAND_SYNTAX_ERROR;
2260 bool physical=strcmp(args[0], "phys")==0;
2261 int (*fn)(struct target *target,
2262 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2267 fn=target_read_phys_memory;
2270 fn=target_read_memory;
2272 if ((argc < 1) || (argc > 2))
2274 return ERROR_COMMAND_SYNTAX_ERROR;
2278 COMMAND_PARSE_NUMBER(u32, args[0], address);
2282 COMMAND_PARSE_NUMBER(uint, args[1], count);
2284 uint8_t *buffer = calloc(count, size);
2286 struct target *target = get_current_target(cmd_ctx);
2287 int retval = fn(target, address, size, count, buffer);
2288 if (ERROR_OK == retval)
2289 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2296 COMMAND_HANDLER(handle_mw_command)
2300 return ERROR_COMMAND_SYNTAX_ERROR;
2302 bool physical=strcmp(args[0], "phys")==0;
2303 int (*fn)(struct target *target,
2304 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2305 const char *cmd_name = CMD_NAME;
2310 fn=target_write_phys_memory;
2313 fn=target_write_memory;
2315 if ((argc < 2) || (argc > 3))
2316 return ERROR_COMMAND_SYNTAX_ERROR;
2319 COMMAND_PARSE_NUMBER(u32, args[0], address);
2322 COMMAND_PARSE_NUMBER(u32, args[1], value);
2326 COMMAND_PARSE_NUMBER(uint, args[2], count);
2328 struct target *target = get_current_target(cmd_ctx);
2330 uint8_t value_buf[4];
2331 switch (cmd_name[6])
2335 target_buffer_set_u32(target, value_buf, value);
2339 target_buffer_set_u16(target, value_buf, value);
2343 value_buf[0] = value;
2346 return ERROR_COMMAND_SYNTAX_ERROR;
2348 for (unsigned i = 0; i < count; i++)
2350 int retval = fn(target,
2351 address + i * wordsize, wordsize, 1, value_buf);
2352 if (ERROR_OK != retval)
2361 static COMMAND_HELPER(parse_load_image_command_args, struct image *image,
2362 uint32_t *min_address, uint32_t *max_address)
2364 if (argc < 1 || argc > 5)
2365 return ERROR_COMMAND_SYNTAX_ERROR;
2367 /* a base address isn't always necessary,
2368 * default to 0x0 (i.e. don't relocate) */
2372 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2373 image->base_address = addr;
2374 image->base_address_set = 1;
2377 image->base_address_set = 0;
2379 image->start_address_set = 0;
2383 COMMAND_PARSE_NUMBER(u32, args[3], *min_address);
2387 COMMAND_PARSE_NUMBER(u32, args[4], *max_address);
2388 // use size (given) to find max (required)
2389 *max_address += *min_address;
2392 if (*min_address > *max_address)
2393 return ERROR_COMMAND_SYNTAX_ERROR;
2398 COMMAND_HANDLER(handle_load_image_command)
2402 uint32_t image_size;
2403 uint32_t min_address = 0;
2404 uint32_t max_address = 0xffffffff;
2408 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_args,
2409 &image, &min_address, &max_address);
2410 if (ERROR_OK != retval)
2413 struct target *target = get_current_target(cmd_ctx);
2415 struct duration bench;
2416 duration_start(&bench);
2418 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2425 for (i = 0; i < image.num_sections; i++)
2427 buffer = malloc(image.sections[i].size);
2430 command_print(cmd_ctx,
2431 "error allocating buffer for section (%d bytes)",
2432 (int)(image.sections[i].size));
2436 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2442 uint32_t offset = 0;
2443 uint32_t length = buf_cnt;
2445 /* DANGER!!! beware of unsigned comparision here!!! */
2447 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2448 (image.sections[i].base_address < max_address))
2450 if (image.sections[i].base_address < min_address)
2452 /* clip addresses below */
2453 offset += min_address-image.sections[i].base_address;
2457 if (image.sections[i].base_address + buf_cnt > max_address)
2459 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2462 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2467 image_size += length;
2468 command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2469 (unsigned int)length,
2470 image.sections[i].base_address + offset);
2476 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2478 command_print(cmd_ctx, "downloaded %" PRIu32 " bytes "
2479 "in %fs (%0.3f kb/s)", image_size,
2480 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2483 image_close(&image);
2489 COMMAND_HANDLER(handle_dump_image_command)
2491 struct fileio fileio;
2493 uint8_t buffer[560];
2497 struct target *target = get_current_target(cmd_ctx);
2501 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2506 COMMAND_PARSE_NUMBER(u32, args[1], address);
2508 COMMAND_PARSE_NUMBER(u32, args[2], size);
2510 if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2515 struct duration bench;
2516 duration_start(&bench);
2518 int retval = ERROR_OK;
2521 uint32_t size_written;
2522 uint32_t this_run_size = (size > 560) ? 560 : size;
2523 retval = target_read_buffer(target, address, this_run_size, buffer);
2524 if (retval != ERROR_OK)
2529 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2530 if (retval != ERROR_OK)
2535 size -= this_run_size;
2536 address += this_run_size;
2539 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2542 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2544 command_print(cmd_ctx,
2545 "dumped %lld bytes in %fs (%0.3f kb/s)", fileio.size,
2546 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2552 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2556 uint32_t image_size;
2559 uint32_t checksum = 0;
2560 uint32_t mem_checksum = 0;
2564 struct target *target = get_current_target(cmd_ctx);
2568 return ERROR_COMMAND_SYNTAX_ERROR;
2573 LOG_ERROR("no target selected");
2577 struct duration bench;
2578 duration_start(&bench);
2583 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2584 image.base_address = addr;
2585 image.base_address_set = 1;
2589 image.base_address_set = 0;
2590 image.base_address = 0x0;
2593 image.start_address_set = 0;
2595 if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2602 for (i = 0; i < image.num_sections; i++)
2604 buffer = malloc(image.sections[i].size);
2607 command_print(cmd_ctx,
2608 "error allocating buffer for section (%d bytes)",
2609 (int)(image.sections[i].size));
2612 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2620 /* calculate checksum of image */
2621 image_calculate_checksum(buffer, buf_cnt, &checksum);
2623 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2624 if (retval != ERROR_OK)
2630 if (checksum != mem_checksum)
2632 /* failed crc checksum, fall back to a binary compare */
2635 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2637 data = (uint8_t*)malloc(buf_cnt);
2639 /* Can we use 32bit word accesses? */
2641 int count = buf_cnt;
2642 if ((count % 4) == 0)
2647 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2648 if (retval == ERROR_OK)
2651 for (t = 0; t < buf_cnt; t++)
2653 if (data[t] != buffer[t])
2655 command_print(cmd_ctx,
2656 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2657 (unsigned)(t + image.sections[i].base_address),
2662 retval = ERROR_FAIL;
2676 command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2677 image.sections[i].base_address,
2682 image_size += buf_cnt;
2685 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2687 command_print(cmd_ctx, "verified %" PRIu32 " bytes "
2688 "in %fs (%0.3f kb/s)", image_size,
2689 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2692 image_close(&image);
2697 COMMAND_HANDLER(handle_verify_image_command)
2699 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2702 COMMAND_HANDLER(handle_test_image_command)
2704 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2707 static int handle_bp_command_list(struct command_context *cmd_ctx)
2709 struct target *target = get_current_target(cmd_ctx);
2710 struct breakpoint *breakpoint = target->breakpoints;
2713 if (breakpoint->type == BKPT_SOFT)
2715 char* buf = buf_to_str(breakpoint->orig_instr,
2716 breakpoint->length, 16);
2717 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2718 breakpoint->address,
2720 breakpoint->set, buf);
2725 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2726 breakpoint->address,
2727 breakpoint->length, breakpoint->set);
2730 breakpoint = breakpoint->next;
2735 static int handle_bp_command_set(struct command_context *cmd_ctx,
2736 uint32_t addr, uint32_t length, int hw)
2738 struct target *target = get_current_target(cmd_ctx);
2739 int retval = breakpoint_add(target, addr, length, hw);
2740 if (ERROR_OK == retval)
2741 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2743 LOG_ERROR("Failure setting breakpoint");
2747 COMMAND_HANDLER(handle_bp_command)
2750 return handle_bp_command_list(cmd_ctx);
2752 if (argc < 2 || argc > 3)
2754 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2755 return ERROR_COMMAND_SYNTAX_ERROR;
2759 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2761 COMMAND_PARSE_NUMBER(u32, args[1], length);
2766 if (strcmp(args[2], "hw") == 0)
2769 return ERROR_COMMAND_SYNTAX_ERROR;
2772 return handle_bp_command_set(cmd_ctx, addr, length, hw);
2775 COMMAND_HANDLER(handle_rbp_command)
2778 return ERROR_COMMAND_SYNTAX_ERROR;
2781 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2783 struct target *target = get_current_target(cmd_ctx);
2784 breakpoint_remove(target, addr);
2789 COMMAND_HANDLER(handle_wp_command)
2791 struct target *target = get_current_target(cmd_ctx);
2795 struct watchpoint *watchpoint = target->watchpoints;
2799 command_print(cmd_ctx, "address: 0x%8.8" PRIx32
2800 ", len: 0x%8.8" PRIx32
2801 ", r/w/a: %i, value: 0x%8.8" PRIx32
2802 ", mask: 0x%8.8" PRIx32,
2803 watchpoint->address,
2805 (int)watchpoint->rw,
2808 watchpoint = watchpoint->next;
2813 enum watchpoint_rw type = WPT_ACCESS;
2815 uint32_t length = 0;
2816 uint32_t data_value = 0x0;
2817 uint32_t data_mask = 0xffffffff;
2822 COMMAND_PARSE_NUMBER(u32, args[4], data_mask);
2825 COMMAND_PARSE_NUMBER(u32, args[3], data_value);
2840 LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2841 return ERROR_COMMAND_SYNTAX_ERROR;
2845 COMMAND_PARSE_NUMBER(u32, args[1], length);
2846 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2850 command_print(cmd_ctx, "usage: wp [address length "
2851 "[(r|w|a) [value [mask]]]]");
2852 return ERROR_COMMAND_SYNTAX_ERROR;
2855 int retval = watchpoint_add(target, addr, length, type,
2856 data_value, data_mask);
2857 if (ERROR_OK != retval)
2858 LOG_ERROR("Failure setting watchpoints");
2863 COMMAND_HANDLER(handle_rwp_command)
2866 return ERROR_COMMAND_SYNTAX_ERROR;
2869 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2871 struct target *target = get_current_target(cmd_ctx);
2872 watchpoint_remove(target, addr);
2879 * Translate a virtual address to a physical address.
2881 * The low-level target implementation must have logged a detailed error
2882 * which is forwarded to telnet/GDB session.
2884 COMMAND_HANDLER(handle_virt2phys_command)
2887 return ERROR_COMMAND_SYNTAX_ERROR;
2890 COMMAND_PARSE_NUMBER(u32, args[0], va);
2893 struct target *target = get_current_target(cmd_ctx);
2894 int retval = target->type->virt2phys(target, va, &pa);
2895 if (retval == ERROR_OK)
2896 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2901 static void writeData(FILE *f, const void *data, size_t len)
2903 size_t written = fwrite(data, 1, len, f);
2905 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2908 static void writeLong(FILE *f, int l)
2911 for (i = 0; i < 4; i++)
2913 char c = (l >> (i*8))&0xff;
2914 writeData(f, &c, 1);
2919 static void writeString(FILE *f, char *s)
2921 writeData(f, s, strlen(s));
2924 /* Dump a gmon.out histogram file. */
2925 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
2928 FILE *f = fopen(filename, "w");
2931 writeString(f, "gmon");
2932 writeLong(f, 0x00000001); /* Version */
2933 writeLong(f, 0); /* padding */
2934 writeLong(f, 0); /* padding */
2935 writeLong(f, 0); /* padding */
2937 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2938 writeData(f, &zero, 1);
2940 /* figure out bucket size */
2941 uint32_t min = samples[0];
2942 uint32_t max = samples[0];
2943 for (i = 0; i < sampleNum; i++)
2945 if (min > samples[i])
2949 if (max < samples[i])
2955 int addressSpace = (max-min + 1);
2957 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2958 uint32_t length = addressSpace;
2959 if (length > maxBuckets)
2961 length = maxBuckets;
2963 int *buckets = malloc(sizeof(int)*length);
2964 if (buckets == NULL)
2969 memset(buckets, 0, sizeof(int)*length);
2970 for (i = 0; i < sampleNum;i++)
2972 uint32_t address = samples[i];
2973 long long a = address-min;
2974 long long b = length-1;
2975 long long c = addressSpace-1;
2976 int index = (a*b)/c; /* danger!!!! int32 overflows */
2980 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2981 writeLong(f, min); /* low_pc */
2982 writeLong(f, max); /* high_pc */
2983 writeLong(f, length); /* # of samples */
2984 writeLong(f, 64000000); /* 64MHz */
2985 writeString(f, "seconds");
2986 for (i = 0; i < (15-strlen("seconds")); i++)
2987 writeData(f, &zero, 1);
2988 writeString(f, "s");
2990 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2992 char *data = malloc(2*length);
2995 for (i = 0; i < length;i++)
3004 data[i*2 + 1]=(val >> 8)&0xff;
3007 writeData(f, data, length * 2);
3017 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
3018 COMMAND_HANDLER(handle_profile_command)
3020 struct target *target = get_current_target(cmd_ctx);
3021 struct timeval timeout, now;
3023 gettimeofday(&timeout, NULL);
3026 return ERROR_COMMAND_SYNTAX_ERROR;
3029 COMMAND_PARSE_NUMBER(uint, args[0], offset);
3031 timeval_add_time(&timeout, offset, 0);
3033 command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3035 static const int maxSample = 10000;
3036 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3037 if (samples == NULL)
3041 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3042 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3047 target_poll(target);
3048 if (target->state == TARGET_HALTED)
3050 uint32_t t=*((uint32_t *)reg->value);
3051 samples[numSamples++]=t;
3052 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3053 target_poll(target);
3054 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3055 } else if (target->state == TARGET_RUNNING)
3057 /* We want to quickly sample the PC. */
3058 if ((retval = target_halt(target)) != ERROR_OK)
3065 command_print(cmd_ctx, "Target not halted or running");
3069 if (retval != ERROR_OK)
3074 gettimeofday(&now, NULL);
3075 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3077 command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3078 if ((retval = target_poll(target)) != ERROR_OK)
3083 if (target->state == TARGET_HALTED)
3085 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3087 if ((retval = target_poll(target)) != ERROR_OK)
3092 writeGmon(samples, numSamples, args[1]);
3093 command_print(cmd_ctx, "Wrote %s", args[1]);
3102 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3105 Jim_Obj *nameObjPtr, *valObjPtr;
3108 namebuf = alloc_printf("%s(%d)", varname, idx);
3112 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3113 valObjPtr = Jim_NewIntObj(interp, val);
3114 if (!nameObjPtr || !valObjPtr)
3120 Jim_IncrRefCount(nameObjPtr);
3121 Jim_IncrRefCount(valObjPtr);
3122 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3123 Jim_DecrRefCount(interp, nameObjPtr);
3124 Jim_DecrRefCount(interp, valObjPtr);
3126 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3130 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3132 struct command_context *context;
3133 struct target *target;
3135 context = Jim_GetAssocData(interp, "context");
3136 if (context == NULL)
3138 LOG_ERROR("mem2array: no command context");
3141 target = get_current_target(context);
3144 LOG_ERROR("mem2array: no current target");
3148 return target_mem2array(interp, target, argc-1, argv + 1);
3151 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3159 const char *varname;
3160 uint8_t buffer[4096];
3164 /* argv[1] = name of array to receive the data
3165 * argv[2] = desired width
3166 * argv[3] = memory address
3167 * argv[4] = count of times to read
3170 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3173 varname = Jim_GetString(argv[0], &len);
3174 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3176 e = Jim_GetLong(interp, argv[1], &l);
3182 e = Jim_GetLong(interp, argv[2], &l);
3187 e = Jim_GetLong(interp, argv[3], &l);
3203 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3204 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3208 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3209 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3212 if ((addr + (len * width)) < addr) {
3213 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3214 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3217 /* absurd transfer size? */
3219 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3220 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3225 ((width == 2) && ((addr & 1) == 0)) ||
3226 ((width == 4) && ((addr & 3) == 0))) {
3230 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3231 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3234 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3245 /* Slurp... in buffer size chunks */
3247 count = len; /* in objects.. */
3248 if (count > (sizeof(buffer)/width)) {
3249 count = (sizeof(buffer)/width);
3252 retval = target_read_memory(target, addr, width, count, buffer);
3253 if (retval != ERROR_OK) {
3255 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3259 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3260 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3264 v = 0; /* shut up gcc */
3265 for (i = 0 ;i < count ;i++, n++) {
3268 v = target_buffer_get_u32(target, &buffer[i*width]);
3271 v = target_buffer_get_u16(target, &buffer[i*width]);
3274 v = buffer[i] & 0x0ff;
3277 new_int_array_element(interp, varname, n, v);
3283 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3288 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3291 Jim_Obj *nameObjPtr, *valObjPtr;
3295 namebuf = alloc_printf("%s(%d)", varname, idx);
3299 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3306 Jim_IncrRefCount(nameObjPtr);
3307 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3308 Jim_DecrRefCount(interp, nameObjPtr);
3310 if (valObjPtr == NULL)
3313 result = Jim_GetLong(interp, valObjPtr, &l);
3314 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3319 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3321 struct command_context *context;
3322 struct target *target;
3324 context = Jim_GetAssocData(interp, "context");
3325 if (context == NULL) {
3326 LOG_ERROR("array2mem: no command context");
3329 target = get_current_target(context);
3330 if (target == NULL) {
3331 LOG_ERROR("array2mem: no current target");
3335 return target_array2mem(interp,target, argc-1, argv + 1);
3337 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3345 const char *varname;
3346 uint8_t buffer[4096];
3350 /* argv[1] = name of array to get the data
3351 * argv[2] = desired width
3352 * argv[3] = memory address
3353 * argv[4] = count to write
3356 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3359 varname = Jim_GetString(argv[0], &len);
3360 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3362 e = Jim_GetLong(interp, argv[1], &l);
3368 e = Jim_GetLong(interp, argv[2], &l);
3373 e = Jim_GetLong(interp, argv[3], &l);
3389 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3390 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3394 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3395 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3398 if ((addr + (len * width)) < addr) {
3399 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3400 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3403 /* absurd transfer size? */
3405 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3406 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3411 ((width == 2) && ((addr & 1) == 0)) ||
3412 ((width == 4) && ((addr & 3) == 0))) {
3416 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3417 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3420 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3431 /* Slurp... in buffer size chunks */
3433 count = len; /* in objects.. */
3434 if (count > (sizeof(buffer)/width)) {
3435 count = (sizeof(buffer)/width);
3438 v = 0; /* shut up gcc */
3439 for (i = 0 ;i < count ;i++, n++) {
3440 get_int_array_element(interp, varname, n, &v);
3443 target_buffer_set_u32(target, &buffer[i*width], v);
3446 target_buffer_set_u16(target, &buffer[i*width], v);
3449 buffer[i] = v & 0x0ff;
3455 retval = target_write_memory(target, addr, width, count, buffer);
3456 if (retval != ERROR_OK) {
3458 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3462 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3463 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3469 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3474 void target_all_handle_event(enum target_event e)
3476 struct target *target;
3478 LOG_DEBUG("**all*targets: event: %d, %s",
3480 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3482 target = all_targets;
3484 target_handle_event(target, e);
3485 target = target->next;
3490 /* FIX? should we propagate errors here rather than printing them
3493 void target_handle_event(struct target *target, enum target_event e)
3495 struct target_event_action *teap;
3497 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3498 if (teap->event == e) {
3499 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3500 target->target_number,
3502 target_get_name(target),
3504 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3505 Jim_GetString(teap->body, NULL));
3506 if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3508 Jim_PrintErrorMessage(interp);
3514 enum target_cfg_param {
3517 TCFG_WORK_AREA_VIRT,
3518 TCFG_WORK_AREA_PHYS,
3519 TCFG_WORK_AREA_SIZE,
3520 TCFG_WORK_AREA_BACKUP,
3523 TCFG_CHAIN_POSITION,
3526 static Jim_Nvp nvp_config_opts[] = {
3527 { .name = "-type", .value = TCFG_TYPE },
3528 { .name = "-event", .value = TCFG_EVENT },
3529 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3530 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3531 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3532 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3533 { .name = "-endian" , .value = TCFG_ENDIAN },
3534 { .name = "-variant", .value = TCFG_VARIANT },
3535 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3537 { .name = NULL, .value = -1 }
3540 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3548 /* parse config or cget options ... */
3549 while (goi->argc > 0) {
3550 Jim_SetEmptyResult(goi->interp);
3551 /* Jim_GetOpt_Debug(goi); */
3553 if (target->type->target_jim_configure) {
3554 /* target defines a configure function */
3555 /* target gets first dibs on parameters */
3556 e = (*(target->type->target_jim_configure))(target, goi);
3565 /* otherwise we 'continue' below */
3567 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3569 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3575 if (goi->isconfigure) {
3576 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3580 if (goi->argc != 0) {
3581 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3585 Jim_SetResultString(goi->interp, target_get_name(target), -1);
3589 if (goi->argc == 0) {
3590 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3594 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3596 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3600 if (goi->isconfigure) {
3601 if (goi->argc != 1) {
3602 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3606 if (goi->argc != 0) {
3607 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3613 struct target_event_action *teap;
3615 teap = target->event_action;
3616 /* replace existing? */
3618 if (teap->event == (enum target_event)n->value) {
3624 if (goi->isconfigure) {
3625 bool replace = true;
3628 teap = calloc(1, sizeof(*teap));
3631 teap->event = n->value;
3632 Jim_GetOpt_Obj(goi, &o);
3634 Jim_DecrRefCount(interp, teap->body);
3636 teap->body = Jim_DuplicateObj(goi->interp, o);
3639 * Tcl/TK - "tk events" have a nice feature.
3640 * See the "BIND" command.
3641 * We should support that here.
3642 * You can specify %X and %Y in the event code.
3643 * The idea is: %T - target name.
3644 * The idea is: %N - target number
3645 * The idea is: %E - event name.
3647 Jim_IncrRefCount(teap->body);
3651 /* add to head of event list */
3652 teap->next = target->event_action;
3653 target->event_action = teap;
3655 Jim_SetEmptyResult(goi->interp);
3659 Jim_SetEmptyResult(goi->interp);
3661 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3668 case TCFG_WORK_AREA_VIRT:
3669 if (goi->isconfigure) {
3670 target_free_all_working_areas(target);
3671 e = Jim_GetOpt_Wide(goi, &w);
3675 target->working_area_virt = w;
3676 target->working_area_virt_spec = true;
3678 if (goi->argc != 0) {
3682 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3686 case TCFG_WORK_AREA_PHYS:
3687 if (goi->isconfigure) {
3688 target_free_all_working_areas(target);
3689 e = Jim_GetOpt_Wide(goi, &w);
3693 target->working_area_phys = w;
3694 target->working_area_phys_spec = true;
3696 if (goi->argc != 0) {
3700 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3704 case TCFG_WORK_AREA_SIZE:
3705 if (goi->isconfigure) {
3706 target_free_all_working_areas(target);
3707 e = Jim_GetOpt_Wide(goi, &w);
3711 target->working_area_size = w;
3713 if (goi->argc != 0) {
3717 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3721 case TCFG_WORK_AREA_BACKUP:
3722 if (goi->isconfigure) {
3723 target_free_all_working_areas(target);
3724 e = Jim_GetOpt_Wide(goi, &w);
3728 /* make this exactly 1 or 0 */
3729 target->backup_working_area = (!!w);
3731 if (goi->argc != 0) {
3735 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3736 /* loop for more e*/
3740 if (goi->isconfigure) {
3741 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3743 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3746 target->endianness = n->value;
3748 if (goi->argc != 0) {
3752 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3753 if (n->name == NULL) {
3754 target->endianness = TARGET_LITTLE_ENDIAN;
3755 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3757 Jim_SetResultString(goi->interp, n->name, -1);
3762 if (goi->isconfigure) {
3763 if (goi->argc < 1) {
3764 Jim_SetResult_sprintf(goi->interp,
3769 if (target->variant) {
3770 free((void *)(target->variant));
3772 e = Jim_GetOpt_String(goi, &cp, NULL);
3773 target->variant = strdup(cp);
3775 if (goi->argc != 0) {
3779 Jim_SetResultString(goi->interp, target->variant,-1);
3782 case TCFG_CHAIN_POSITION:
3783 if (goi->isconfigure) {
3785 struct jtag_tap *tap;
3786 target_free_all_working_areas(target);
3787 e = Jim_GetOpt_Obj(goi, &o);
3791 tap = jtag_tap_by_jim_obj(goi->interp, o);
3795 /* make this exactly 1 or 0 */
3798 if (goi->argc != 0) {
3802 Jim_SetResultString(interp, target->tap->dotted_name, -1);
3803 /* loop for more e*/
3806 } /* while (goi->argc) */
3809 /* done - we return */
3813 /** this is the 'tcl' handler for the target specific command */
3814 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3819 uint8_t target_buf[32];
3821 struct target *target;
3822 struct command_context *cmd_ctx;
3829 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3830 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3831 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3832 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3840 TS_CMD_INVOKE_EVENT,
3843 static const Jim_Nvp target_options[] = {
3844 { .name = "configure", .value = TS_CMD_CONFIGURE },
3845 { .name = "cget", .value = TS_CMD_CGET },
3846 { .name = "mww", .value = TS_CMD_MWW },
3847 { .name = "mwh", .value = TS_CMD_MWH },
3848 { .name = "mwb", .value = TS_CMD_MWB },
3849 { .name = "mdw", .value = TS_CMD_MDW },
3850 { .name = "mdh", .value = TS_CMD_MDH },
3851 { .name = "mdb", .value = TS_CMD_MDB },
3852 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3853 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3854 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3855 { .name = "curstate", .value = TS_CMD_CURSTATE },
3857 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3858 { .name = "arp_poll", .value = TS_CMD_POLL },
3859 { .name = "arp_reset", .value = TS_CMD_RESET },
3860 { .name = "arp_halt", .value = TS_CMD_HALT },
3861 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3862 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3864 { .name = NULL, .value = -1 },
3867 /* go past the "command" */
3868 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3870 target = Jim_CmdPrivData(goi.interp);
3871 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3873 /* commands here are in an NVP table */
3874 e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3876 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3879 /* Assume blank result */
3880 Jim_SetEmptyResult(goi.interp);
3883 case TS_CMD_CONFIGURE:
3885 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3888 goi.isconfigure = 1;
3889 return target_configure(&goi, target);
3891 // some things take params
3893 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3896 goi.isconfigure = 0;
3897 return target_configure(&goi, target);
3905 * argv[3] = optional count.
3908 if ((goi.argc == 2) || (goi.argc == 3)) {
3912 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3916 e = Jim_GetOpt_Wide(&goi, &a);
3921 e = Jim_GetOpt_Wide(&goi, &b);
3925 if (goi.argc == 3) {
3926 e = Jim_GetOpt_Wide(&goi, &c);
3936 target_buffer_set_u32(target, target_buf, b);
3940 target_buffer_set_u16(target, target_buf, b);
3944 target_buffer_set_u8(target, target_buf, b);
3948 for (x = 0 ; x < c ; x++) {
3949 e = target_write_memory(target, a, b, 1, target_buf);
3950 if (e != ERROR_OK) {
3951 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3964 /* argv[0] = command
3966 * argv[2] = optional count
3968 if ((goi.argc == 2) || (goi.argc == 3)) {
3969 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3972 e = Jim_GetOpt_Wide(&goi, &a);
3977 e = Jim_GetOpt_Wide(&goi, &c);
3984 b = 1; /* shut up gcc */
3997 /* convert to "bytes" */
3999 /* count is now in 'BYTES' */
4005 e = target_read_memory(target, a, b, y / b, target_buf);
4006 if (e != ERROR_OK) {
4007 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4011 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4014 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
4015 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
4016 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4018 for (; (x < 16) ; x += 4) {
4019 Jim_fprintf(interp, interp->cookie_stdout, " ");
4023 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
4024 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
4025 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4027 for (; (x < 16) ; x += 2) {
4028 Jim_fprintf(interp, interp->cookie_stdout, " ");
4033 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4034 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4035 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4037 for (; (x < 16) ; x += 1) {
4038 Jim_fprintf(interp, interp->cookie_stdout, " ");
4042 /* ascii-ify the bytes */
4043 for (x = 0 ; x < y ; x++) {
4044 if ((target_buf[x] >= 0x20) &&
4045 (target_buf[x] <= 0x7e)) {
4049 target_buf[x] = '.';
4054 target_buf[x] = ' ';
4059 /* print - with a newline */
4060 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4066 case TS_CMD_MEM2ARRAY:
4067 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4069 case TS_CMD_ARRAY2MEM:
4070 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4072 case TS_CMD_EXAMINE:
4074 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4077 if (!target->tap->enabled)
4078 goto err_tap_disabled;
4079 e = target->type->examine(target);
4080 if (e != ERROR_OK) {
4081 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4087 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4090 if (!target->tap->enabled)
4091 goto err_tap_disabled;
4092 if (!(target_was_examined(target))) {
4093 e = ERROR_TARGET_NOT_EXAMINED;
4095 e = target->type->poll(target);
4097 if (e != ERROR_OK) {
4098 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4105 if (goi.argc != 2) {
4106 Jim_WrongNumArgs(interp, 2, argv,
4107 "([tT]|[fF]|assert|deassert) BOOL");
4110 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4112 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4115 /* the halt or not param */
4116 e = Jim_GetOpt_Wide(&goi, &a);
4120 if (!target->tap->enabled)
4121 goto err_tap_disabled;
4122 if (!target->type->assert_reset
4123 || !target->type->deassert_reset) {
4124 Jim_SetResult_sprintf(interp,
4125 "No target-specific reset for %s",
4129 /* determine if we should halt or not. */
4130 target->reset_halt = !!a;
4131 /* When this happens - all workareas are invalid. */
4132 target_free_all_working_areas_restore(target, 0);
4135 if (n->value == NVP_ASSERT) {
4136 e = target->type->assert_reset(target);
4138 e = target->type->deassert_reset(target);
4140 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4143 Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4146 if (!target->tap->enabled)
4147 goto err_tap_disabled;
4148 e = target->type->halt(target);
4149 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4150 case TS_CMD_WAITSTATE:
4151 /* params: <name> statename timeoutmsecs */
4152 if (goi.argc != 2) {
4153 Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4156 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4158 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4161 e = Jim_GetOpt_Wide(&goi, &a);
4165 if (!target->tap->enabled)
4166 goto err_tap_disabled;
4167 e = target_wait_state(target, n->value, a);
4168 if (e != ERROR_OK) {
4169 Jim_SetResult_sprintf(goi.interp,
4170 "target: %s wait %s fails (%d) %s",
4173 e, target_strerror_safe(e));
4178 case TS_CMD_EVENTLIST:
4179 /* List for human, Events defined for this target.
4180 * scripts/programs should use 'name cget -event NAME'
4183 struct target_event_action *teap;
4184 teap = target->event_action;
4185 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4186 target->target_number,
4188 command_print(cmd_ctx, "%-25s | Body", "Event");
4189 command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4191 command_print(cmd_ctx,
4193 Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4194 Jim_GetString(teap->body, NULL));
4197 command_print(cmd_ctx, "***END***");
4200 case TS_CMD_CURSTATE:
4201 if (goi.argc != 0) {
4202 Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4205 Jim_SetResultString(goi.interp,
4206 target_state_name( target ),
4209 case TS_CMD_INVOKE_EVENT:
4210 if (goi.argc != 1) {
4211 Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4214 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4216 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4219 target_handle_event(target, n->value);
4225 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4229 static int target_create(Jim_GetOptInfo *goi)
4237 struct target *target;
4238 struct command_context *cmd_ctx;
4240 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4241 if (goi->argc < 3) {
4242 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4247 Jim_GetOpt_Obj(goi, &new_cmd);
4248 /* does this command exist? */
4249 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4251 cp = Jim_GetString(new_cmd, NULL);
4252 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4257 e = Jim_GetOpt_String(goi, &cp2, NULL);
4259 /* now does target type exist */
4260 for (x = 0 ; target_types[x] ; x++) {
4261 if (0 == strcmp(cp, target_types[x]->name)) {
4266 if (target_types[x] == NULL) {
4267 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4268 for (x = 0 ; target_types[x] ; x++) {
4269 if (target_types[x + 1]) {
4270 Jim_AppendStrings(goi->interp,
4271 Jim_GetResult(goi->interp),
4272 target_types[x]->name,
4275 Jim_AppendStrings(goi->interp,
4276 Jim_GetResult(goi->interp),
4278 target_types[x]->name,NULL);
4285 target = calloc(1,sizeof(struct target));
4286 /* set target number */
4287 target->target_number = new_target_number();
4289 /* allocate memory for each unique target type */
4290 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4292 memcpy(target->type, target_types[x], sizeof(struct target_type));
4294 /* will be set by "-endian" */
4295 target->endianness = TARGET_ENDIAN_UNKNOWN;
4297 target->working_area = 0x0;
4298 target->working_area_size = 0x0;
4299 target->working_areas = NULL;
4300 target->backup_working_area = 0;
4302 target->state = TARGET_UNKNOWN;
4303 target->debug_reason = DBG_REASON_UNDEFINED;
4304 target->reg_cache = NULL;
4305 target->breakpoints = NULL;
4306 target->watchpoints = NULL;
4307 target->next = NULL;
4308 target->arch_info = NULL;
4310 target->display = 1;
4312 target->halt_issued = false;
4314 /* initialize trace information */
4315 target->trace_info = malloc(sizeof(struct trace));
4316 target->trace_info->num_trace_points = 0;
4317 target->trace_info->trace_points_size = 0;
4318 target->trace_info->trace_points = NULL;
4319 target->trace_info->trace_history_size = 0;
4320 target->trace_info->trace_history = NULL;
4321 target->trace_info->trace_history_pos = 0;
4322 target->trace_info->trace_history_overflowed = 0;
4324 target->dbgmsg = NULL;
4325 target->dbg_msg_enabled = 0;
4327 target->endianness = TARGET_ENDIAN_UNKNOWN;
4329 /* Do the rest as "configure" options */
4330 goi->isconfigure = 1;
4331 e = target_configure(goi, target);
4333 if (target->tap == NULL)
4335 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4345 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4346 /* default endian to little if not specified */
4347 target->endianness = TARGET_LITTLE_ENDIAN;
4350 /* incase variant is not set */
4351 if (!target->variant)
4352 target->variant = strdup("");
4354 /* create the target specific commands */
4355 if (target->type->register_commands) {
4356 (*(target->type->register_commands))(cmd_ctx);
4358 if (target->type->target_create) {
4359 (*(target->type->target_create))(target, goi->interp);
4362 /* append to end of list */
4364 struct target **tpp;
4365 tpp = &(all_targets);
4367 tpp = &((*tpp)->next);
4372 cp = Jim_GetString(new_cmd, NULL);
4373 target->cmd_name = strdup(cp);
4375 /* now - create the new target name command */
4376 e = Jim_CreateCommand(goi->interp,
4379 tcl_target_func, /* C function */
4380 target, /* private data */
4381 NULL); /* no del proc */
4386 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4390 struct command_context *cmd_ctx;
4391 struct target *target;
4394 /* TG = target generic */
4402 const char *target_cmds[] = {
4403 "create", "types", "names", "current", "number",
4405 NULL /* terminate */
4408 LOG_DEBUG("Target command params:");
4409 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4411 cmd_ctx = Jim_GetAssocData(interp, "context");
4413 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4415 if (goi.argc == 0) {
4416 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4420 /* Jim_GetOpt_Debug(&goi); */
4421 r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4428 Jim_Panic(goi.interp,"Why am I here?");
4430 case TG_CMD_CURRENT:
4431 if (goi.argc != 0) {
4432 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4435 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4438 if (goi.argc != 0) {
4439 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4442 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4443 for (x = 0 ; target_types[x] ; x++) {
4444 Jim_ListAppendElement(goi.interp,
4445 Jim_GetResult(goi.interp),
4446 Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4450 if (goi.argc != 0) {
4451 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4454 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4455 target = all_targets;
4457 Jim_ListAppendElement(goi.interp,
4458 Jim_GetResult(goi.interp),
4459 Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4460 target = target->next;
4465 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4468 return target_create(&goi);
4471 /* It's OK to remove this mechanism sometime after August 2010 or so */
4472 LOG_WARNING("don't use numbers as target identifiers; use names");
4473 if (goi.argc != 1) {
4474 Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4477 e = Jim_GetOpt_Wide(&goi, &w);
4481 for (x = 0, target = all_targets; target; target = target->next, x++) {
4482 if (target->target_number == w)
4485 if (target == NULL) {
4486 Jim_SetResult_sprintf(goi.interp,
4487 "Target: number %d does not exist", (int)(w));
4490 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4493 if (goi.argc != 0) {
4494 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4497 for (x = 0, target = all_targets; target; target = target->next, x++)
4499 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4515 static int fastload_num;
4516 static struct FastLoad *fastload;
4518 static void free_fastload(void)
4520 if (fastload != NULL)
4523 for (i = 0; i < fastload_num; i++)
4525 if (fastload[i].data)
4526 free(fastload[i].data);
4536 COMMAND_HANDLER(handle_fast_load_image_command)
4540 uint32_t image_size;
4541 uint32_t min_address = 0;
4542 uint32_t max_address = 0xffffffff;
4547 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_args,
4548 &image, &min_address, &max_address);
4549 if (ERROR_OK != retval)
4552 struct duration bench;
4553 duration_start(&bench);
4555 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4562 fastload_num = image.num_sections;
4563 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4564 if (fastload == NULL)
4566 image_close(&image);
4569 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4570 for (i = 0; i < image.num_sections; i++)
4572 buffer = malloc(image.sections[i].size);
4575 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4576 (int)(image.sections[i].size));
4580 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4586 uint32_t offset = 0;
4587 uint32_t length = buf_cnt;
4590 /* DANGER!!! beware of unsigned comparision here!!! */
4592 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4593 (image.sections[i].base_address < max_address))
4595 if (image.sections[i].base_address < min_address)
4597 /* clip addresses below */
4598 offset += min_address-image.sections[i].base_address;
4602 if (image.sections[i].base_address + buf_cnt > max_address)
4604 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4607 fastload[i].address = image.sections[i].base_address + offset;
4608 fastload[i].data = malloc(length);
4609 if (fastload[i].data == NULL)
4614 memcpy(fastload[i].data, buffer + offset, length);
4615 fastload[i].length = length;
4617 image_size += length;
4618 command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4619 (unsigned int)length,
4620 ((unsigned int)(image.sections[i].base_address + offset)));
4626 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4628 command_print(cmd_ctx, "Loaded %" PRIu32 " bytes "
4629 "in %fs (%0.3f kb/s)", image_size,
4630 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4632 command_print(cmd_ctx,
4633 "WARNING: image has not been loaded to target!"
4634 "You can issue a 'fast_load' to finish loading.");
4637 image_close(&image);
4639 if (retval != ERROR_OK)
4647 COMMAND_HANDLER(handle_fast_load_command)
4650 return ERROR_COMMAND_SYNTAX_ERROR;
4651 if (fastload == NULL)
4653 LOG_ERROR("No image in memory");
4657 int ms = timeval_ms();
4659 int retval = ERROR_OK;
4660 for (i = 0; i < fastload_num;i++)
4662 struct target *target = get_current_target(cmd_ctx);
4663 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4664 (unsigned int)(fastload[i].address),
4665 (unsigned int)(fastload[i].length));
4666 if (retval == ERROR_OK)
4668 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4670 size += fastload[i].length;
4672 int after = timeval_ms();
4673 command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4677 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4679 struct command_context *context;
4680 struct target *target;
4683 context = Jim_GetAssocData(interp, "context");
4684 if (context == NULL) {
4685 LOG_ERROR("array2mem: no command context");
4688 target = get_current_target(context);
4689 if (target == NULL) {
4690 LOG_ERROR("array2mem: no current target");
4694 if ((argc < 6) || (argc > 7))
4708 e = Jim_GetLong(interp, argv[1], &l);
4714 e = Jim_GetLong(interp, argv[2], &l);
4720 e = Jim_GetLong(interp, argv[3], &l);
4726 e = Jim_GetLong(interp, argv[4], &l);
4732 e = Jim_GetLong(interp, argv[5], &l);
4742 e = Jim_GetLong(interp, argv[6], &l);
4748 retval = target_mcr(target, cpnum, op1, op2, CRn, CRm, value);
4749 if (retval != ERROR_OK)
4753 retval = target_mrc(target, cpnum, op1, op2, CRn, CRm, &value);
4754 if (retval != ERROR_OK)
4757 Jim_SetResult(interp, Jim_NewIntObj(interp, value));
4763 int target_register_commands(struct command_context *cmd_ctx)
4766 register_command(cmd_ctx, NULL, "targets",
4767 handle_targets_command, COMMAND_EXEC,
4768 "change current command line target (one parameter) "
4769 "or list targets (no parameters)");
4771 register_jim(cmd_ctx, "target", jim_target, "configure target");
4776 int target_register_user_commands(struct command_context *cmd_ctx)
4778 int retval = ERROR_OK;
4779 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
4782 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
4785 register_command(cmd_ctx, NULL, "profile",
4786 handle_profile_command, COMMAND_EXEC,
4787 "profiling samples the CPU PC");
4789 register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array,
4790 "read memory and return as a TCL array for script processing "
4791 "<ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
4793 register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem,
4794 "convert a TCL array to memory locations and write the values "
4795 "<ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
4797 register_command(cmd_ctx, NULL, "fast_load_image",
4798 handle_fast_load_image_command, COMMAND_ANY,
4799 "same args as load_image, image stored in memory "
4800 "- mainly for profiling purposes");
4802 register_command(cmd_ctx, NULL, "fast_load",
4803 handle_fast_load_command, COMMAND_ANY,
4804 "loads active fast load image to current target "
4805 "- mainly for profiling purposes");
4807 /** @todo don't register virt2phys() unless target supports it */
4808 register_command(cmd_ctx, NULL, "virt2phys",
4809 handle_virt2phys_command, COMMAND_ANY,
4810 "translate a virtual address into a physical address");
4812 register_command(cmd_ctx, NULL, "reg",
4813 handle_reg_command, COMMAND_EXEC,
4814 "display or set a register");
4816 register_command(cmd_ctx, NULL, "poll",
4817 handle_poll_command, COMMAND_EXEC,
4818 "poll target state");
4819 register_command(cmd_ctx, NULL, "wait_halt",
4820 handle_wait_halt_command, COMMAND_EXEC,
4821 "wait for target halt [time (s)]");
4822 register_command(cmd_ctx, NULL, "halt",
4823 handle_halt_command, COMMAND_EXEC,
4825 register_command(cmd_ctx, NULL, "resume",
4826 handle_resume_command, COMMAND_EXEC,
4827 "resume target [addr]");
4828 register_command(cmd_ctx, NULL, "reset",
4829 handle_reset_command, COMMAND_EXEC,
4830 "reset target [run | halt | init] - default is run");
4831 register_command(cmd_ctx, NULL, "soft_reset_halt",
4832 handle_soft_reset_halt_command, COMMAND_EXEC,
4833 "halt the target and do a soft reset");
4835 register_command(cmd_ctx, NULL, "step",
4836 handle_step_command, COMMAND_EXEC,
4837 "step one instruction from current PC or [addr]");
4839 register_command(cmd_ctx, NULL, "mdw",
4840 handle_md_command, COMMAND_EXEC,
4841 "display memory words [phys] <addr> [count]");
4842 register_command(cmd_ctx, NULL, "mdh",
4843 handle_md_command, COMMAND_EXEC,
4844 "display memory half-words [phys] <addr> [count]");
4845 register_command(cmd_ctx, NULL, "mdb",
4846 handle_md_command, COMMAND_EXEC,
4847 "display memory bytes [phys] <addr> [count]");
4849 register_command(cmd_ctx, NULL, "mww",
4850 handle_mw_command, COMMAND_EXEC,
4851 "write memory word [phys] <addr> <value> [count]");
4852 register_command(cmd_ctx, NULL, "mwh",
4853 handle_mw_command, COMMAND_EXEC,
4854 "write memory half-word [phys] <addr> <value> [count]");
4855 register_command(cmd_ctx, NULL, "mwb",
4856 handle_mw_command, COMMAND_EXEC,
4857 "write memory byte [phys] <addr> <value> [count]");
4859 register_command(cmd_ctx, NULL, "bp",
4860 handle_bp_command, COMMAND_EXEC,
4861 "list or set breakpoint [<address> <length> [hw]]");
4862 register_command(cmd_ctx, NULL, "rbp",
4863 handle_rbp_command, COMMAND_EXEC,
4864 "remove breakpoint <address>");
4866 register_command(cmd_ctx, NULL, "wp",
4867 handle_wp_command, COMMAND_EXEC,
4868 "list or set watchpoint "
4869 "[<address> <length> <r/w/a> [value] [mask]]");
4870 register_command(cmd_ctx, NULL, "rwp",
4871 handle_rwp_command, COMMAND_EXEC,
4872 "remove watchpoint <address>");
4874 register_command(cmd_ctx, NULL, "load_image",
4875 handle_load_image_command, COMMAND_EXEC,
4876 "load_image <file> <address> "
4877 "['bin'|'ihex'|'elf'|'s19'] [min_address] [max_length]");
4878 register_command(cmd_ctx, NULL, "dump_image",
4879 handle_dump_image_command, COMMAND_EXEC,
4880 "dump_image <file> <address> <size>");
4881 register_command(cmd_ctx, NULL, "verify_image",
4882 handle_verify_image_command, COMMAND_EXEC,
4883 "verify_image <file> [offset] [type]");
4884 register_command(cmd_ctx, NULL, "test_image",
4885 handle_test_image_command, COMMAND_EXEC,
4886 "test_image <file> [offset] [type]");