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);
647 /// @returns @c true if the target has been examined.
648 bool target_was_examined(struct target *target)
650 return target->type->examined;
652 /// Sets the @c examined flag for the given target.
653 void target_set_examined(struct target *target)
655 target->type->examined = true;
657 // Reset the @c examined flag for the given target.
658 void target_reset_examined(struct target *target)
660 target->type->examined = false;
665 static int default_mrc(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
667 LOG_ERROR("Not implemented: %s", __func__);
671 static int default_mcr(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
673 LOG_ERROR("Not implemented: %s", __func__);
677 static int arm_cp_check(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm)
680 if (!target_was_examined(target))
682 LOG_ERROR("Target not examined yet");
686 if ((cpnum <0) || (cpnum > 15))
688 LOG_ERROR("Illegal co-processor %d", cpnum);
694 LOG_ERROR("Illegal op1");
700 LOG_ERROR("Illegal op2");
706 LOG_ERROR("Illegal CRn");
712 LOG_ERROR("Illegal CRm");
719 int target_mrc(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
723 retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
724 if (retval != ERROR_OK)
727 return target->type->mrc(target, cpnum, op1, op2, CRn, CRm, value);
730 int target_mcr(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
734 retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
735 if (retval != ERROR_OK)
738 return target->type->mcr(target, cpnum, op1, op2, CRn, CRm, value);
742 err_read_phys_memory(struct target *target, uint32_t address,
743 uint32_t size, uint32_t count, uint8_t *buffer)
745 LOG_ERROR("Not implemented: %s", __func__);
750 err_write_phys_memory(struct target *target, uint32_t address,
751 uint32_t size, uint32_t count, uint8_t *buffer)
753 LOG_ERROR("Not implemented: %s", __func__);
757 int target_init(struct command_context *cmd_ctx)
759 struct target *target;
762 for (target = all_targets; target; target = target->next) {
763 struct target_type *type = target->type;
765 target_reset_examined(target);
766 if (target->type->examine == NULL)
768 target->type->examine = default_examine;
771 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
773 LOG_ERROR("target '%s' init failed", target_get_name(target));
778 * @todo MCR/MRC are ARM-specific; don't require them in
779 * all targets, or for ARMs without coprocessors.
781 if (target->type->mcr == NULL)
783 target->type->mcr = default_mcr;
786 /* FIX! multiple targets will generally register global commands
787 * multiple times. Only register this one if *one* of the
788 * targets need the command. Hmm... make it a command on the
789 * Jim Tcl target object?
791 register_jim(cmd_ctx, "mcr", jim_mcrmrc, "write coprocessor <cpnum> <op1> <op2> <CRn> <CRm> <value>");
794 if (target->type->mrc == NULL)
796 target->type->mrc = default_mrc;
799 register_jim(cmd_ctx, "mrc", jim_mcrmrc, "read coprocessor <cpnum> <op1> <op2> <CRn> <CRm>");
804 * @todo get rid of those *memory_imp() methods, now that all
805 * callers are using target_*_memory() accessors ... and make
806 * sure the "physical" paths handle the same issues.
809 /* a non-invasive way(in terms of patches) to add some code that
810 * runs before the type->write/read_memory implementation
812 target->type->write_memory_imp = target->type->write_memory;
813 target->type->write_memory = target_write_memory_imp;
814 target->type->read_memory_imp = target->type->read_memory;
815 target->type->read_memory = target_read_memory_imp;
816 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
817 target->type->soft_reset_halt = target_soft_reset_halt_imp;
818 target->type->run_algorithm_imp = target->type->run_algorithm;
819 target->type->run_algorithm = target_run_algorithm_imp;
821 /* Sanity-check MMU support ... stub in what we must, to help
822 * implement it in stages, but warn if we need to do so.
825 if (type->write_phys_memory == NULL) {
826 LOG_ERROR("type '%s' is missing %s",
828 "write_phys_memory");
829 type->write_phys_memory = err_write_phys_memory;
831 if (type->read_phys_memory == NULL) {
832 LOG_ERROR("type '%s' is missing %s",
835 type->read_phys_memory = err_read_phys_memory;
837 if (type->virt2phys == NULL) {
838 LOG_ERROR("type '%s' is missing %s",
841 type->virt2phys = identity_virt2phys;
844 /* Make sure no-MMU targets all behave the same: make no
845 * distinction between physical and virtual addresses, and
846 * ensure that virt2phys() is always an identity mapping.
849 if (type->write_phys_memory
850 || type->read_phys_memory
852 LOG_WARNING("type '%s' has broken MMU hooks",
856 type->write_phys_memory = type->write_memory;
857 type->read_phys_memory = type->read_memory;
858 type->virt2phys = identity_virt2phys;
864 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
866 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
873 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
875 struct target_event_callback **callbacks_p = &target_event_callbacks;
877 if (callback == NULL)
879 return ERROR_INVALID_ARGUMENTS;
884 while ((*callbacks_p)->next)
885 callbacks_p = &((*callbacks_p)->next);
886 callbacks_p = &((*callbacks_p)->next);
889 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
890 (*callbacks_p)->callback = callback;
891 (*callbacks_p)->priv = priv;
892 (*callbacks_p)->next = NULL;
897 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
899 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
902 if (callback == NULL)
904 return ERROR_INVALID_ARGUMENTS;
909 while ((*callbacks_p)->next)
910 callbacks_p = &((*callbacks_p)->next);
911 callbacks_p = &((*callbacks_p)->next);
914 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
915 (*callbacks_p)->callback = callback;
916 (*callbacks_p)->periodic = periodic;
917 (*callbacks_p)->time_ms = time_ms;
919 gettimeofday(&now, NULL);
920 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
921 time_ms -= (time_ms % 1000);
922 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
923 if ((*callbacks_p)->when.tv_usec > 1000000)
925 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
926 (*callbacks_p)->when.tv_sec += 1;
929 (*callbacks_p)->priv = priv;
930 (*callbacks_p)->next = NULL;
935 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
937 struct target_event_callback **p = &target_event_callbacks;
938 struct target_event_callback *c = target_event_callbacks;
940 if (callback == NULL)
942 return ERROR_INVALID_ARGUMENTS;
947 struct target_event_callback *next = c->next;
948 if ((c->callback == callback) && (c->priv == priv))
962 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
964 struct target_timer_callback **p = &target_timer_callbacks;
965 struct target_timer_callback *c = target_timer_callbacks;
967 if (callback == NULL)
969 return ERROR_INVALID_ARGUMENTS;
974 struct target_timer_callback *next = c->next;
975 if ((c->callback == callback) && (c->priv == priv))
989 int target_call_event_callbacks(struct target *target, enum target_event event)
991 struct target_event_callback *callback = target_event_callbacks;
992 struct target_event_callback *next_callback;
994 if (event == TARGET_EVENT_HALTED)
996 /* execute early halted first */
997 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1000 LOG_DEBUG("target event %i (%s)",
1002 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1004 target_handle_event(target, event);
1008 next_callback = callback->next;
1009 callback->callback(target, event, callback->priv);
1010 callback = next_callback;
1016 static int target_timer_callback_periodic_restart(
1017 struct target_timer_callback *cb, struct timeval *now)
1019 int time_ms = cb->time_ms;
1020 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1021 time_ms -= (time_ms % 1000);
1022 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1023 if (cb->when.tv_usec > 1000000)
1025 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1026 cb->when.tv_sec += 1;
1031 static int target_call_timer_callback(struct target_timer_callback *cb,
1032 struct timeval *now)
1034 cb->callback(cb->priv);
1037 return target_timer_callback_periodic_restart(cb, now);
1039 return target_unregister_timer_callback(cb->callback, cb->priv);
1042 static int target_call_timer_callbacks_check_time(int checktime)
1047 gettimeofday(&now, NULL);
1049 struct target_timer_callback *callback = target_timer_callbacks;
1052 // cleaning up may unregister and free this callback
1053 struct target_timer_callback *next_callback = callback->next;
1055 bool call_it = callback->callback &&
1056 ((!checktime && callback->periodic) ||
1057 now.tv_sec > callback->when.tv_sec ||
1058 (now.tv_sec == callback->when.tv_sec &&
1059 now.tv_usec >= callback->when.tv_usec));
1063 int retval = target_call_timer_callback(callback, &now);
1064 if (retval != ERROR_OK)
1068 callback = next_callback;
1074 int target_call_timer_callbacks(void)
1076 return target_call_timer_callbacks_check_time(1);
1079 /* invoke periodic callbacks immediately */
1080 int target_call_timer_callbacks_now(void)
1082 return target_call_timer_callbacks_check_time(0);
1085 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1087 struct working_area *c = target->working_areas;
1088 struct working_area *new_wa = NULL;
1090 /* Reevaluate working area address based on MMU state*/
1091 if (target->working_areas == NULL)
1096 retval = target->type->mmu(target, &enabled);
1097 if (retval != ERROR_OK)
1103 if (target->working_area_phys_spec) {
1104 LOG_DEBUG("MMU disabled, using physical "
1105 "address for working memory 0x%08x",
1106 (unsigned)target->working_area_phys);
1107 target->working_area = target->working_area_phys;
1109 LOG_ERROR("No working memory available. "
1110 "Specify -work-area-phys to target.");
1111 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1114 if (target->working_area_virt_spec) {
1115 LOG_DEBUG("MMU enabled, using virtual "
1116 "address for working memory 0x%08x",
1117 (unsigned)target->working_area_virt);
1118 target->working_area = target->working_area_virt;
1120 LOG_ERROR("No working memory available. "
1121 "Specify -work-area-virt to target.");
1122 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1127 /* only allocate multiples of 4 byte */
1130 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1131 size = (size + 3) & (~3);
1134 /* see if there's already a matching working area */
1137 if ((c->free) && (c->size == size))
1145 /* if not, allocate a new one */
1148 struct working_area **p = &target->working_areas;
1149 uint32_t first_free = target->working_area;
1150 uint32_t free_size = target->working_area_size;
1152 c = target->working_areas;
1155 first_free += c->size;
1156 free_size -= c->size;
1161 if (free_size < size)
1163 LOG_WARNING("not enough working area available(requested %u, free %u)",
1164 (unsigned)(size), (unsigned)(free_size));
1165 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1168 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1170 new_wa = malloc(sizeof(struct working_area));
1171 new_wa->next = NULL;
1172 new_wa->size = size;
1173 new_wa->address = first_free;
1175 if (target->backup_working_area)
1178 new_wa->backup = malloc(new_wa->size);
1179 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1181 free(new_wa->backup);
1188 new_wa->backup = NULL;
1191 /* put new entry in list */
1195 /* mark as used, and return the new (reused) area */
1200 new_wa->user = area;
1205 int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1210 if (restore && target->backup_working_area)
1213 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1219 /* mark user pointer invalid */
1226 int target_free_working_area(struct target *target, struct working_area *area)
1228 return target_free_working_area_restore(target, area, 1);
1231 /* free resources and restore memory, if restoring memory fails,
1232 * free up resources anyway
1234 void target_free_all_working_areas_restore(struct target *target, int restore)
1236 struct working_area *c = target->working_areas;
1240 struct working_area *next = c->next;
1241 target_free_working_area_restore(target, c, restore);
1251 target->working_areas = NULL;
1254 void target_free_all_working_areas(struct target *target)
1256 target_free_all_working_areas_restore(target, 1);
1259 int target_arch_state(struct target *target)
1264 LOG_USER("No target has been configured");
1268 LOG_USER("target state: %s", target_state_name( target ));
1270 if (target->state != TARGET_HALTED)
1273 retval = target->type->arch_state(target);
1277 /* Single aligned words are guaranteed to use 16 or 32 bit access
1278 * mode respectively, otherwise data is handled as quickly as
1281 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1284 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1285 (int)size, (unsigned)address);
1287 if (!target_was_examined(target))
1289 LOG_ERROR("Target not examined yet");
1297 if ((address + size - 1) < address)
1299 /* GDB can request this when e.g. PC is 0xfffffffc*/
1300 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1306 if (((address % 2) == 0) && (size == 2))
1308 return target_write_memory(target, address, 2, 1, buffer);
1311 /* handle unaligned head bytes */
1314 uint32_t unaligned = 4 - (address % 4);
1316 if (unaligned > size)
1319 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1322 buffer += unaligned;
1323 address += unaligned;
1327 /* handle aligned words */
1330 int aligned = size - (size % 4);
1332 /* use bulk writes above a certain limit. This may have to be changed */
1335 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1340 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1349 /* handle tail writes of less than 4 bytes */
1352 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1359 /* Single aligned words are guaranteed to use 16 or 32 bit access
1360 * mode respectively, otherwise data is handled as quickly as
1363 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1366 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1367 (int)size, (unsigned)address);
1369 if (!target_was_examined(target))
1371 LOG_ERROR("Target not examined yet");
1379 if ((address + size - 1) < address)
1381 /* GDB can request this when e.g. PC is 0xfffffffc*/
1382 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1388 if (((address % 2) == 0) && (size == 2))
1390 return target_read_memory(target, address, 2, 1, buffer);
1393 /* handle unaligned head bytes */
1396 uint32_t unaligned = 4 - (address % 4);
1398 if (unaligned > size)
1401 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1404 buffer += unaligned;
1405 address += unaligned;
1409 /* handle aligned words */
1412 int aligned = size - (size % 4);
1414 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1422 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1425 int aligned = size - (size%2);
1426 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1427 if (retval != ERROR_OK)
1434 /* handle tail writes of less than 4 bytes */
1437 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1444 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1449 uint32_t checksum = 0;
1450 if (!target_was_examined(target))
1452 LOG_ERROR("Target not examined yet");
1456 if ((retval = target->type->checksum_memory(target, address,
1457 size, &checksum)) != ERROR_OK)
1459 buffer = malloc(size);
1462 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1463 return ERROR_INVALID_ARGUMENTS;
1465 retval = target_read_buffer(target, address, size, buffer);
1466 if (retval != ERROR_OK)
1472 /* convert to target endianess */
1473 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1475 uint32_t target_data;
1476 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1477 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1480 retval = image_calculate_checksum(buffer, size, &checksum);
1489 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1492 if (!target_was_examined(target))
1494 LOG_ERROR("Target not examined yet");
1498 if (target->type->blank_check_memory == 0)
1499 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1501 retval = target->type->blank_check_memory(target, address, size, blank);
1506 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1508 uint8_t value_buf[4];
1509 if (!target_was_examined(target))
1511 LOG_ERROR("Target not examined yet");
1515 int retval = target_read_memory(target, address, 4, 1, value_buf);
1517 if (retval == ERROR_OK)
1519 *value = target_buffer_get_u32(target, value_buf);
1520 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1527 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1534 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1536 uint8_t value_buf[2];
1537 if (!target_was_examined(target))
1539 LOG_ERROR("Target not examined yet");
1543 int retval = target_read_memory(target, address, 2, 1, value_buf);
1545 if (retval == ERROR_OK)
1547 *value = target_buffer_get_u16(target, value_buf);
1548 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1555 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1562 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1564 int retval = target_read_memory(target, address, 1, 1, value);
1565 if (!target_was_examined(target))
1567 LOG_ERROR("Target not examined yet");
1571 if (retval == ERROR_OK)
1573 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1580 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1587 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1590 uint8_t value_buf[4];
1591 if (!target_was_examined(target))
1593 LOG_ERROR("Target not examined yet");
1597 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1601 target_buffer_set_u32(target, value_buf, value);
1602 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1604 LOG_DEBUG("failed: %i", retval);
1610 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1613 uint8_t value_buf[2];
1614 if (!target_was_examined(target))
1616 LOG_ERROR("Target not examined yet");
1620 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1624 target_buffer_set_u16(target, value_buf, value);
1625 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1627 LOG_DEBUG("failed: %i", retval);
1633 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1636 if (!target_was_examined(target))
1638 LOG_ERROR("Target not examined yet");
1642 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1645 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1647 LOG_DEBUG("failed: %i", retval);
1653 COMMAND_HANDLER(handle_targets_command)
1655 struct target *target = all_targets;
1659 target = get_target(args[0]);
1660 if (target == NULL) {
1661 command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1664 if (!target->tap->enabled) {
1665 command_print(cmd_ctx,"Target: TAP %s is disabled, "
1666 "can't be the current target\n",
1667 target->tap->dotted_name);
1671 cmd_ctx->current_target = target->target_number;
1676 target = all_targets;
1677 command_print(cmd_ctx, " TargetName Type Endian TapName State ");
1678 command_print(cmd_ctx, "-- ------------------ ---------- ------ ------------------ ------------");
1684 if (target->tap->enabled)
1685 state = target_state_name( target );
1687 state = "tap-disabled";
1689 if (cmd_ctx->current_target == target->target_number)
1692 /* keep columns lined up to match the headers above */
1693 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1694 target->target_number,
1697 target_get_name(target),
1698 Jim_Nvp_value2name_simple(nvp_target_endian,
1699 target->endianness)->name,
1700 target->tap->dotted_name,
1702 target = target->next;
1708 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1710 static int powerDropout;
1711 static int srstAsserted;
1713 static int runPowerRestore;
1714 static int runPowerDropout;
1715 static int runSrstAsserted;
1716 static int runSrstDeasserted;
1718 static int sense_handler(void)
1720 static int prevSrstAsserted = 0;
1721 static int prevPowerdropout = 0;
1724 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1728 powerRestored = prevPowerdropout && !powerDropout;
1731 runPowerRestore = 1;
1734 long long current = timeval_ms();
1735 static long long lastPower = 0;
1736 int waitMore = lastPower + 2000 > current;
1737 if (powerDropout && !waitMore)
1739 runPowerDropout = 1;
1740 lastPower = current;
1743 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1747 srstDeasserted = prevSrstAsserted && !srstAsserted;
1749 static long long lastSrst = 0;
1750 waitMore = lastSrst + 2000 > current;
1751 if (srstDeasserted && !waitMore)
1753 runSrstDeasserted = 1;
1757 if (!prevSrstAsserted && srstAsserted)
1759 runSrstAsserted = 1;
1762 prevSrstAsserted = srstAsserted;
1763 prevPowerdropout = powerDropout;
1765 if (srstDeasserted || powerRestored)
1767 /* Other than logging the event we can't do anything here.
1768 * Issuing a reset is a particularly bad idea as we might
1769 * be inside a reset already.
1776 static void target_call_event_callbacks_all(enum target_event e) {
1777 struct target *target;
1778 target = all_targets;
1780 target_call_event_callbacks(target, e);
1781 target = target->next;
1785 /* process target state changes */
1786 int handle_target(void *priv)
1788 int retval = ERROR_OK;
1790 /* we do not want to recurse here... */
1791 static int recursive = 0;
1796 /* danger! running these procedures can trigger srst assertions and power dropouts.
1797 * We need to avoid an infinite loop/recursion here and we do that by
1798 * clearing the flags after running these events.
1800 int did_something = 0;
1801 if (runSrstAsserted)
1803 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1804 Jim_Eval(interp, "srst_asserted");
1807 if (runSrstDeasserted)
1809 Jim_Eval(interp, "srst_deasserted");
1812 if (runPowerDropout)
1814 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1815 Jim_Eval(interp, "power_dropout");
1818 if (runPowerRestore)
1820 Jim_Eval(interp, "power_restore");
1826 /* clear detect flags */
1830 /* clear action flags */
1832 runSrstAsserted = 0;
1833 runSrstDeasserted = 0;
1834 runPowerRestore = 0;
1835 runPowerDropout = 0;
1840 /* Poll targets for state changes unless that's globally disabled.
1841 * Skip targets that are currently disabled.
1843 for (struct target *target = all_targets;
1844 is_jtag_poll_safe() && target;
1845 target = target->next)
1847 if (!target->tap->enabled)
1850 /* only poll target if we've got power and srst isn't asserted */
1851 if (!powerDropout && !srstAsserted)
1853 /* polling may fail silently until the target has been examined */
1854 if ((retval = target_poll(target)) != ERROR_OK)
1856 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1865 COMMAND_HANDLER(handle_reg_command)
1867 struct target *target;
1868 struct reg *reg = NULL;
1874 target = get_current_target(cmd_ctx);
1876 /* list all available registers for the current target */
1879 struct reg_cache *cache = target->reg_cache;
1886 command_print(cmd_ctx, "===== %s", cache->name);
1888 for (i = 0, reg = cache->reg_list;
1889 i < cache->num_regs;
1890 i++, reg++, count++)
1892 /* only print cached values if they are valid */
1894 value = buf_to_str(reg->value,
1896 command_print(cmd_ctx,
1897 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1905 command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1910 cache = cache->next;
1916 /* access a single register by its ordinal number */
1917 if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1920 COMMAND_PARSE_NUMBER(uint, args[0], num);
1922 struct reg_cache *cache = target->reg_cache;
1927 for (i = 0; i < cache->num_regs; i++)
1929 if (count++ == (int)num)
1931 reg = &cache->reg_list[i];
1937 cache = cache->next;
1942 command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1945 } else /* access a single register by its name */
1947 reg = register_get_by_name(target->reg_cache, args[0], 1);
1951 command_print(cmd_ctx, "register %s not found in current target", args[0]);
1956 /* display a register */
1957 if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1959 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1962 if (reg->valid == 0)
1964 struct reg_arch_type *arch_type = register_get_arch_type(reg->arch_type);
1965 arch_type->get(reg);
1967 value = buf_to_str(reg->value, reg->size, 16);
1968 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1973 /* set register value */
1976 uint8_t *buf = malloc(CEIL(reg->size, 8));
1977 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1979 struct reg_arch_type *arch_type = register_get_arch_type(reg->arch_type);
1980 arch_type->set(reg, buf);
1982 value = buf_to_str(reg->value, reg->size, 16);
1983 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1991 command_print(cmd_ctx, "usage: reg <#|name> [value]");
1996 COMMAND_HANDLER(handle_poll_command)
1998 int retval = ERROR_OK;
1999 struct target *target = get_current_target(cmd_ctx);
2003 command_print(cmd_ctx, "background polling: %s",
2004 jtag_poll_get_enabled() ? "on" : "off");
2005 command_print(cmd_ctx, "TAP: %s (%s)",
2006 target->tap->dotted_name,
2007 target->tap->enabled ? "enabled" : "disabled");
2008 if (!target->tap->enabled)
2010 if ((retval = target_poll(target)) != ERROR_OK)
2012 if ((retval = target_arch_state(target)) != ERROR_OK)
2018 if (strcmp(args[0], "on") == 0)
2020 jtag_poll_set_enabled(true);
2022 else if (strcmp(args[0], "off") == 0)
2024 jtag_poll_set_enabled(false);
2028 command_print(cmd_ctx, "arg is \"on\" or \"off\"");
2032 return ERROR_COMMAND_SYNTAX_ERROR;
2038 COMMAND_HANDLER(handle_wait_halt_command)
2041 return ERROR_COMMAND_SYNTAX_ERROR;
2046 int retval = parse_uint(args[0], &ms);
2047 if (ERROR_OK != retval)
2049 command_print(cmd_ctx, "usage: %s [seconds]", CMD_NAME);
2050 return ERROR_COMMAND_SYNTAX_ERROR;
2052 // convert seconds (given) to milliseconds (needed)
2056 struct target *target = get_current_target(cmd_ctx);
2057 return target_wait_state(target, TARGET_HALTED, ms);
2060 /* wait for target state to change. The trick here is to have a low
2061 * latency for short waits and not to suck up all the CPU time
2064 * After 500ms, keep_alive() is invoked
2066 int target_wait_state(struct target *target, enum target_state state, int ms)
2069 long long then = 0, cur;
2074 if ((retval = target_poll(target)) != ERROR_OK)
2076 if (target->state == state)
2084 then = timeval_ms();
2085 LOG_DEBUG("waiting for target %s...",
2086 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2094 if ((cur-then) > ms)
2096 LOG_ERROR("timed out while waiting for target %s",
2097 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2105 COMMAND_HANDLER(handle_halt_command)
2109 struct target *target = get_current_target(cmd_ctx);
2110 int retval = target_halt(target);
2111 if (ERROR_OK != retval)
2117 retval = parse_uint(args[0], &wait);
2118 if (ERROR_OK != retval)
2119 return ERROR_COMMAND_SYNTAX_ERROR;
2124 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2127 COMMAND_HANDLER(handle_soft_reset_halt_command)
2129 struct target *target = get_current_target(cmd_ctx);
2131 LOG_USER("requesting target halt and executing a soft reset");
2133 target->type->soft_reset_halt(target);
2138 COMMAND_HANDLER(handle_reset_command)
2141 return ERROR_COMMAND_SYNTAX_ERROR;
2143 enum target_reset_mode reset_mode = RESET_RUN;
2147 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2148 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2149 return ERROR_COMMAND_SYNTAX_ERROR;
2151 reset_mode = n->value;
2154 /* reset *all* targets */
2155 return target_process_reset(cmd_ctx, reset_mode);
2159 COMMAND_HANDLER(handle_resume_command)
2163 return ERROR_COMMAND_SYNTAX_ERROR;
2165 struct target *target = get_current_target(cmd_ctx);
2166 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2168 /* with no args, resume from current pc, addr = 0,
2169 * with one arguments, addr = args[0],
2170 * handle breakpoints, not debugging */
2174 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2178 return target_resume(target, current, addr, 1, 0);
2181 COMMAND_HANDLER(handle_step_command)
2184 return ERROR_COMMAND_SYNTAX_ERROR;
2188 /* with no args, step from current pc, addr = 0,
2189 * with one argument addr = args[0],
2190 * handle breakpoints, debugging */
2195 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2199 struct target *target = get_current_target(cmd_ctx);
2201 return target->type->step(target, current_pc, addr, 1);
2204 static void handle_md_output(struct command_context *cmd_ctx,
2205 struct target *target, uint32_t address, unsigned size,
2206 unsigned count, const uint8_t *buffer)
2208 const unsigned line_bytecnt = 32;
2209 unsigned line_modulo = line_bytecnt / size;
2211 char output[line_bytecnt * 4 + 1];
2212 unsigned output_len = 0;
2214 const char *value_fmt;
2216 case 4: value_fmt = "%8.8x "; break;
2217 case 2: value_fmt = "%4.2x "; break;
2218 case 1: value_fmt = "%2.2x "; break;
2220 LOG_ERROR("invalid memory read size: %u", size);
2224 for (unsigned i = 0; i < count; i++)
2226 if (i % line_modulo == 0)
2228 output_len += snprintf(output + output_len,
2229 sizeof(output) - output_len,
2231 (unsigned)(address + (i*size)));
2235 const uint8_t *value_ptr = buffer + i * size;
2237 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2238 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2239 case 1: value = *value_ptr;
2241 output_len += snprintf(output + output_len,
2242 sizeof(output) - output_len,
2245 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2247 command_print(cmd_ctx, "%s", output);
2253 COMMAND_HANDLER(handle_md_command)
2256 return ERROR_COMMAND_SYNTAX_ERROR;
2259 const char *cmd_name = CMD_NAME;
2260 switch (cmd_name[6]) {
2261 case 'w': size = 4; break;
2262 case 'h': size = 2; break;
2263 case 'b': size = 1; break;
2264 default: return ERROR_COMMAND_SYNTAX_ERROR;
2267 bool physical=strcmp(args[0], "phys")==0;
2268 int (*fn)(struct target *target,
2269 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2274 fn=target_read_phys_memory;
2277 fn=target_read_memory;
2279 if ((argc < 1) || (argc > 2))
2281 return ERROR_COMMAND_SYNTAX_ERROR;
2285 COMMAND_PARSE_NUMBER(u32, args[0], address);
2289 COMMAND_PARSE_NUMBER(uint, args[1], count);
2291 uint8_t *buffer = calloc(count, size);
2293 struct target *target = get_current_target(cmd_ctx);
2294 int retval = fn(target, address, size, count, buffer);
2295 if (ERROR_OK == retval)
2296 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2303 COMMAND_HANDLER(handle_mw_command)
2307 return ERROR_COMMAND_SYNTAX_ERROR;
2309 bool physical=strcmp(args[0], "phys")==0;
2310 int (*fn)(struct target *target,
2311 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2312 const char *cmd_name = CMD_NAME;
2317 fn=target_write_phys_memory;
2320 fn=target_write_memory;
2322 if ((argc < 2) || (argc > 3))
2323 return ERROR_COMMAND_SYNTAX_ERROR;
2326 COMMAND_PARSE_NUMBER(u32, args[0], address);
2329 COMMAND_PARSE_NUMBER(u32, args[1], value);
2333 COMMAND_PARSE_NUMBER(uint, args[2], count);
2335 struct target *target = get_current_target(cmd_ctx);
2337 uint8_t value_buf[4];
2338 switch (cmd_name[6])
2342 target_buffer_set_u32(target, value_buf, value);
2346 target_buffer_set_u16(target, value_buf, value);
2350 value_buf[0] = value;
2353 return ERROR_COMMAND_SYNTAX_ERROR;
2355 for (unsigned i = 0; i < count; i++)
2357 int retval = fn(target,
2358 address + i * wordsize, wordsize, 1, value_buf);
2359 if (ERROR_OK != retval)
2368 static COMMAND_HELPER(parse_load_image_command_args, struct image *image,
2369 uint32_t *min_address, uint32_t *max_address)
2371 if (argc < 1 || argc > 5)
2372 return ERROR_COMMAND_SYNTAX_ERROR;
2374 /* a base address isn't always necessary,
2375 * default to 0x0 (i.e. don't relocate) */
2379 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2380 image->base_address = addr;
2381 image->base_address_set = 1;
2384 image->base_address_set = 0;
2386 image->start_address_set = 0;
2390 COMMAND_PARSE_NUMBER(u32, args[3], *min_address);
2394 COMMAND_PARSE_NUMBER(u32, args[4], *max_address);
2395 // use size (given) to find max (required)
2396 *max_address += *min_address;
2399 if (*min_address > *max_address)
2400 return ERROR_COMMAND_SYNTAX_ERROR;
2405 COMMAND_HANDLER(handle_load_image_command)
2409 uint32_t image_size;
2410 uint32_t min_address = 0;
2411 uint32_t max_address = 0xffffffff;
2415 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_args,
2416 &image, &min_address, &max_address);
2417 if (ERROR_OK != retval)
2420 struct target *target = get_current_target(cmd_ctx);
2422 struct duration bench;
2423 duration_start(&bench);
2425 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2432 for (i = 0; i < image.num_sections; i++)
2434 buffer = malloc(image.sections[i].size);
2437 command_print(cmd_ctx,
2438 "error allocating buffer for section (%d bytes)",
2439 (int)(image.sections[i].size));
2443 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2449 uint32_t offset = 0;
2450 uint32_t length = buf_cnt;
2452 /* DANGER!!! beware of unsigned comparision here!!! */
2454 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2455 (image.sections[i].base_address < max_address))
2457 if (image.sections[i].base_address < min_address)
2459 /* clip addresses below */
2460 offset += min_address-image.sections[i].base_address;
2464 if (image.sections[i].base_address + buf_cnt > max_address)
2466 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2469 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2474 image_size += length;
2475 command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2476 (unsigned int)length,
2477 image.sections[i].base_address + offset);
2483 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2485 command_print(cmd_ctx, "downloaded %" PRIu32 " bytes "
2486 "in %fs (%0.3f kb/s)", image_size,
2487 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2490 image_close(&image);
2496 COMMAND_HANDLER(handle_dump_image_command)
2498 struct fileio fileio;
2500 uint8_t buffer[560];
2504 struct target *target = get_current_target(cmd_ctx);
2508 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2513 COMMAND_PARSE_NUMBER(u32, args[1], address);
2515 COMMAND_PARSE_NUMBER(u32, args[2], size);
2517 if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2522 struct duration bench;
2523 duration_start(&bench);
2525 int retval = ERROR_OK;
2528 uint32_t size_written;
2529 uint32_t this_run_size = (size > 560) ? 560 : size;
2530 retval = target_read_buffer(target, address, this_run_size, buffer);
2531 if (retval != ERROR_OK)
2536 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2537 if (retval != ERROR_OK)
2542 size -= this_run_size;
2543 address += this_run_size;
2546 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2549 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2551 command_print(cmd_ctx,
2552 "dumped %lld bytes in %fs (%0.3f kb/s)", fileio.size,
2553 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2559 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2563 uint32_t image_size;
2566 uint32_t checksum = 0;
2567 uint32_t mem_checksum = 0;
2571 struct target *target = get_current_target(cmd_ctx);
2575 return ERROR_COMMAND_SYNTAX_ERROR;
2580 LOG_ERROR("no target selected");
2584 struct duration bench;
2585 duration_start(&bench);
2590 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2591 image.base_address = addr;
2592 image.base_address_set = 1;
2596 image.base_address_set = 0;
2597 image.base_address = 0x0;
2600 image.start_address_set = 0;
2602 if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2609 for (i = 0; i < image.num_sections; i++)
2611 buffer = malloc(image.sections[i].size);
2614 command_print(cmd_ctx,
2615 "error allocating buffer for section (%d bytes)",
2616 (int)(image.sections[i].size));
2619 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2627 /* calculate checksum of image */
2628 image_calculate_checksum(buffer, buf_cnt, &checksum);
2630 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2631 if (retval != ERROR_OK)
2637 if (checksum != mem_checksum)
2639 /* failed crc checksum, fall back to a binary compare */
2642 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2644 data = (uint8_t*)malloc(buf_cnt);
2646 /* Can we use 32bit word accesses? */
2648 int count = buf_cnt;
2649 if ((count % 4) == 0)
2654 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2655 if (retval == ERROR_OK)
2658 for (t = 0; t < buf_cnt; t++)
2660 if (data[t] != buffer[t])
2662 command_print(cmd_ctx,
2663 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2664 (unsigned)(t + image.sections[i].base_address),
2669 retval = ERROR_FAIL;
2683 command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2684 image.sections[i].base_address,
2689 image_size += buf_cnt;
2692 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2694 command_print(cmd_ctx, "verified %" PRIu32 " bytes "
2695 "in %fs (%0.3f kb/s)", image_size,
2696 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2699 image_close(&image);
2704 COMMAND_HANDLER(handle_verify_image_command)
2706 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2709 COMMAND_HANDLER(handle_test_image_command)
2711 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2714 static int handle_bp_command_list(struct command_context *cmd_ctx)
2716 struct target *target = get_current_target(cmd_ctx);
2717 struct breakpoint *breakpoint = target->breakpoints;
2720 if (breakpoint->type == BKPT_SOFT)
2722 char* buf = buf_to_str(breakpoint->orig_instr,
2723 breakpoint->length, 16);
2724 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2725 breakpoint->address,
2727 breakpoint->set, buf);
2732 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2733 breakpoint->address,
2734 breakpoint->length, breakpoint->set);
2737 breakpoint = breakpoint->next;
2742 static int handle_bp_command_set(struct command_context *cmd_ctx,
2743 uint32_t addr, uint32_t length, int hw)
2745 struct target *target = get_current_target(cmd_ctx);
2746 int retval = breakpoint_add(target, addr, length, hw);
2747 if (ERROR_OK == retval)
2748 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2750 LOG_ERROR("Failure setting breakpoint");
2754 COMMAND_HANDLER(handle_bp_command)
2757 return handle_bp_command_list(cmd_ctx);
2759 if (argc < 2 || argc > 3)
2761 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2762 return ERROR_COMMAND_SYNTAX_ERROR;
2766 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2768 COMMAND_PARSE_NUMBER(u32, args[1], length);
2773 if (strcmp(args[2], "hw") == 0)
2776 return ERROR_COMMAND_SYNTAX_ERROR;
2779 return handle_bp_command_set(cmd_ctx, addr, length, hw);
2782 COMMAND_HANDLER(handle_rbp_command)
2785 return ERROR_COMMAND_SYNTAX_ERROR;
2788 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2790 struct target *target = get_current_target(cmd_ctx);
2791 breakpoint_remove(target, addr);
2796 COMMAND_HANDLER(handle_wp_command)
2798 struct target *target = get_current_target(cmd_ctx);
2802 struct watchpoint *watchpoint = target->watchpoints;
2806 command_print(cmd_ctx, "address: 0x%8.8" PRIx32
2807 ", len: 0x%8.8" PRIx32
2808 ", r/w/a: %i, value: 0x%8.8" PRIx32
2809 ", mask: 0x%8.8" PRIx32,
2810 watchpoint->address,
2812 (int)watchpoint->rw,
2815 watchpoint = watchpoint->next;
2820 enum watchpoint_rw type = WPT_ACCESS;
2822 uint32_t length = 0;
2823 uint32_t data_value = 0x0;
2824 uint32_t data_mask = 0xffffffff;
2829 COMMAND_PARSE_NUMBER(u32, args[4], data_mask);
2832 COMMAND_PARSE_NUMBER(u32, args[3], data_value);
2847 LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2848 return ERROR_COMMAND_SYNTAX_ERROR;
2852 COMMAND_PARSE_NUMBER(u32, args[1], length);
2853 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2857 command_print(cmd_ctx, "usage: wp [address length "
2858 "[(r|w|a) [value [mask]]]]");
2859 return ERROR_COMMAND_SYNTAX_ERROR;
2862 int retval = watchpoint_add(target, addr, length, type,
2863 data_value, data_mask);
2864 if (ERROR_OK != retval)
2865 LOG_ERROR("Failure setting watchpoints");
2870 COMMAND_HANDLER(handle_rwp_command)
2873 return ERROR_COMMAND_SYNTAX_ERROR;
2876 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2878 struct target *target = get_current_target(cmd_ctx);
2879 watchpoint_remove(target, addr);
2886 * Translate a virtual address to a physical address.
2888 * The low-level target implementation must have logged a detailed error
2889 * which is forwarded to telnet/GDB session.
2891 COMMAND_HANDLER(handle_virt2phys_command)
2894 return ERROR_COMMAND_SYNTAX_ERROR;
2897 COMMAND_PARSE_NUMBER(u32, args[0], va);
2900 struct target *target = get_current_target(cmd_ctx);
2901 int retval = target->type->virt2phys(target, va, &pa);
2902 if (retval == ERROR_OK)
2903 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2908 static void writeData(FILE *f, const void *data, size_t len)
2910 size_t written = fwrite(data, 1, len, f);
2912 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2915 static void writeLong(FILE *f, int l)
2918 for (i = 0; i < 4; i++)
2920 char c = (l >> (i*8))&0xff;
2921 writeData(f, &c, 1);
2926 static void writeString(FILE *f, char *s)
2928 writeData(f, s, strlen(s));
2931 /* Dump a gmon.out histogram file. */
2932 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
2935 FILE *f = fopen(filename, "w");
2938 writeString(f, "gmon");
2939 writeLong(f, 0x00000001); /* Version */
2940 writeLong(f, 0); /* padding */
2941 writeLong(f, 0); /* padding */
2942 writeLong(f, 0); /* padding */
2944 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2945 writeData(f, &zero, 1);
2947 /* figure out bucket size */
2948 uint32_t min = samples[0];
2949 uint32_t max = samples[0];
2950 for (i = 0; i < sampleNum; i++)
2952 if (min > samples[i])
2956 if (max < samples[i])
2962 int addressSpace = (max-min + 1);
2964 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2965 uint32_t length = addressSpace;
2966 if (length > maxBuckets)
2968 length = maxBuckets;
2970 int *buckets = malloc(sizeof(int)*length);
2971 if (buckets == NULL)
2976 memset(buckets, 0, sizeof(int)*length);
2977 for (i = 0; i < sampleNum;i++)
2979 uint32_t address = samples[i];
2980 long long a = address-min;
2981 long long b = length-1;
2982 long long c = addressSpace-1;
2983 int index = (a*b)/c; /* danger!!!! int32 overflows */
2987 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2988 writeLong(f, min); /* low_pc */
2989 writeLong(f, max); /* high_pc */
2990 writeLong(f, length); /* # of samples */
2991 writeLong(f, 64000000); /* 64MHz */
2992 writeString(f, "seconds");
2993 for (i = 0; i < (15-strlen("seconds")); i++)
2994 writeData(f, &zero, 1);
2995 writeString(f, "s");
2997 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2999 char *data = malloc(2*length);
3002 for (i = 0; i < length;i++)
3011 data[i*2 + 1]=(val >> 8)&0xff;
3014 writeData(f, data, length * 2);
3024 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
3025 COMMAND_HANDLER(handle_profile_command)
3027 struct target *target = get_current_target(cmd_ctx);
3028 struct timeval timeout, now;
3030 gettimeofday(&timeout, NULL);
3033 return ERROR_COMMAND_SYNTAX_ERROR;
3036 COMMAND_PARSE_NUMBER(uint, args[0], offset);
3038 timeval_add_time(&timeout, offset, 0);
3040 command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3042 static const int maxSample = 10000;
3043 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3044 if (samples == NULL)
3048 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3049 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3054 target_poll(target);
3055 if (target->state == TARGET_HALTED)
3057 uint32_t t=*((uint32_t *)reg->value);
3058 samples[numSamples++]=t;
3059 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3060 target_poll(target);
3061 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3062 } else if (target->state == TARGET_RUNNING)
3064 /* We want to quickly sample the PC. */
3065 if ((retval = target_halt(target)) != ERROR_OK)
3072 command_print(cmd_ctx, "Target not halted or running");
3076 if (retval != ERROR_OK)
3081 gettimeofday(&now, NULL);
3082 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3084 command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3085 if ((retval = target_poll(target)) != ERROR_OK)
3090 if (target->state == TARGET_HALTED)
3092 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3094 if ((retval = target_poll(target)) != ERROR_OK)
3099 writeGmon(samples, numSamples, args[1]);
3100 command_print(cmd_ctx, "Wrote %s", args[1]);
3109 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3112 Jim_Obj *nameObjPtr, *valObjPtr;
3115 namebuf = alloc_printf("%s(%d)", varname, idx);
3119 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3120 valObjPtr = Jim_NewIntObj(interp, val);
3121 if (!nameObjPtr || !valObjPtr)
3127 Jim_IncrRefCount(nameObjPtr);
3128 Jim_IncrRefCount(valObjPtr);
3129 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3130 Jim_DecrRefCount(interp, nameObjPtr);
3131 Jim_DecrRefCount(interp, valObjPtr);
3133 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3137 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3139 struct command_context *context;
3140 struct target *target;
3142 context = Jim_GetAssocData(interp, "context");
3143 if (context == NULL)
3145 LOG_ERROR("mem2array: no command context");
3148 target = get_current_target(context);
3151 LOG_ERROR("mem2array: no current target");
3155 return target_mem2array(interp, target, argc-1, argv + 1);
3158 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3166 const char *varname;
3167 uint8_t buffer[4096];
3171 /* argv[1] = name of array to receive the data
3172 * argv[2] = desired width
3173 * argv[3] = memory address
3174 * argv[4] = count of times to read
3177 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3180 varname = Jim_GetString(argv[0], &len);
3181 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3183 e = Jim_GetLong(interp, argv[1], &l);
3189 e = Jim_GetLong(interp, argv[2], &l);
3194 e = Jim_GetLong(interp, argv[3], &l);
3210 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3211 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3215 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3216 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3219 if ((addr + (len * width)) < addr) {
3220 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3221 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3224 /* absurd transfer size? */
3226 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3227 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3232 ((width == 2) && ((addr & 1) == 0)) ||
3233 ((width == 4) && ((addr & 3) == 0))) {
3237 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3238 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3241 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3252 /* Slurp... in buffer size chunks */
3254 count = len; /* in objects.. */
3255 if (count > (sizeof(buffer)/width)) {
3256 count = (sizeof(buffer)/width);
3259 retval = target_read_memory(target, addr, width, count, buffer);
3260 if (retval != ERROR_OK) {
3262 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3266 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3267 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3271 v = 0; /* shut up gcc */
3272 for (i = 0 ;i < count ;i++, n++) {
3275 v = target_buffer_get_u32(target, &buffer[i*width]);
3278 v = target_buffer_get_u16(target, &buffer[i*width]);
3281 v = buffer[i] & 0x0ff;
3284 new_int_array_element(interp, varname, n, v);
3290 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3295 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3298 Jim_Obj *nameObjPtr, *valObjPtr;
3302 namebuf = alloc_printf("%s(%d)", varname, idx);
3306 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3313 Jim_IncrRefCount(nameObjPtr);
3314 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3315 Jim_DecrRefCount(interp, nameObjPtr);
3317 if (valObjPtr == NULL)
3320 result = Jim_GetLong(interp, valObjPtr, &l);
3321 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3326 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3328 struct command_context *context;
3329 struct target *target;
3331 context = Jim_GetAssocData(interp, "context");
3332 if (context == NULL) {
3333 LOG_ERROR("array2mem: no command context");
3336 target = get_current_target(context);
3337 if (target == NULL) {
3338 LOG_ERROR("array2mem: no current target");
3342 return target_array2mem(interp,target, argc-1, argv + 1);
3344 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3352 const char *varname;
3353 uint8_t buffer[4096];
3357 /* argv[1] = name of array to get the data
3358 * argv[2] = desired width
3359 * argv[3] = memory address
3360 * argv[4] = count to write
3363 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3366 varname = Jim_GetString(argv[0], &len);
3367 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3369 e = Jim_GetLong(interp, argv[1], &l);
3375 e = Jim_GetLong(interp, argv[2], &l);
3380 e = Jim_GetLong(interp, argv[3], &l);
3396 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3397 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3401 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3402 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3405 if ((addr + (len * width)) < addr) {
3406 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3407 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3410 /* absurd transfer size? */
3412 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3413 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3418 ((width == 2) && ((addr & 1) == 0)) ||
3419 ((width == 4) && ((addr & 3) == 0))) {
3423 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3424 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3427 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3438 /* Slurp... in buffer size chunks */
3440 count = len; /* in objects.. */
3441 if (count > (sizeof(buffer)/width)) {
3442 count = (sizeof(buffer)/width);
3445 v = 0; /* shut up gcc */
3446 for (i = 0 ;i < count ;i++, n++) {
3447 get_int_array_element(interp, varname, n, &v);
3450 target_buffer_set_u32(target, &buffer[i*width], v);
3453 target_buffer_set_u16(target, &buffer[i*width], v);
3456 buffer[i] = v & 0x0ff;
3462 retval = target_write_memory(target, addr, width, count, buffer);
3463 if (retval != ERROR_OK) {
3465 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3469 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3470 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3476 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3481 void target_all_handle_event(enum target_event e)
3483 struct target *target;
3485 LOG_DEBUG("**all*targets: event: %d, %s",
3487 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3489 target = all_targets;
3491 target_handle_event(target, e);
3492 target = target->next;
3497 /* FIX? should we propagate errors here rather than printing them
3500 void target_handle_event(struct target *target, enum target_event e)
3502 struct target_event_action *teap;
3504 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3505 if (teap->event == e) {
3506 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3507 target->target_number,
3509 target_get_name(target),
3511 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3512 Jim_GetString(teap->body, NULL));
3513 if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3515 Jim_PrintErrorMessage(interp);
3521 enum target_cfg_param {
3524 TCFG_WORK_AREA_VIRT,
3525 TCFG_WORK_AREA_PHYS,
3526 TCFG_WORK_AREA_SIZE,
3527 TCFG_WORK_AREA_BACKUP,
3530 TCFG_CHAIN_POSITION,
3533 static Jim_Nvp nvp_config_opts[] = {
3534 { .name = "-type", .value = TCFG_TYPE },
3535 { .name = "-event", .value = TCFG_EVENT },
3536 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3537 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3538 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3539 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3540 { .name = "-endian" , .value = TCFG_ENDIAN },
3541 { .name = "-variant", .value = TCFG_VARIANT },
3542 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3544 { .name = NULL, .value = -1 }
3547 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3555 /* parse config or cget options ... */
3556 while (goi->argc > 0) {
3557 Jim_SetEmptyResult(goi->interp);
3558 /* Jim_GetOpt_Debug(goi); */
3560 if (target->type->target_jim_configure) {
3561 /* target defines a configure function */
3562 /* target gets first dibs on parameters */
3563 e = (*(target->type->target_jim_configure))(target, goi);
3572 /* otherwise we 'continue' below */
3574 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3576 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3582 if (goi->isconfigure) {
3583 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3587 if (goi->argc != 0) {
3588 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3592 Jim_SetResultString(goi->interp, target_get_name(target), -1);
3596 if (goi->argc == 0) {
3597 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3601 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3603 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3607 if (goi->isconfigure) {
3608 if (goi->argc != 1) {
3609 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3613 if (goi->argc != 0) {
3614 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3620 struct target_event_action *teap;
3622 teap = target->event_action;
3623 /* replace existing? */
3625 if (teap->event == (enum target_event)n->value) {
3631 if (goi->isconfigure) {
3632 bool replace = true;
3635 teap = calloc(1, sizeof(*teap));
3638 teap->event = n->value;
3639 Jim_GetOpt_Obj(goi, &o);
3641 Jim_DecrRefCount(interp, teap->body);
3643 teap->body = Jim_DuplicateObj(goi->interp, o);
3646 * Tcl/TK - "tk events" have a nice feature.
3647 * See the "BIND" command.
3648 * We should support that here.
3649 * You can specify %X and %Y in the event code.
3650 * The idea is: %T - target name.
3651 * The idea is: %N - target number
3652 * The idea is: %E - event name.
3654 Jim_IncrRefCount(teap->body);
3658 /* add to head of event list */
3659 teap->next = target->event_action;
3660 target->event_action = teap;
3662 Jim_SetEmptyResult(goi->interp);
3666 Jim_SetEmptyResult(goi->interp);
3668 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3675 case TCFG_WORK_AREA_VIRT:
3676 if (goi->isconfigure) {
3677 target_free_all_working_areas(target);
3678 e = Jim_GetOpt_Wide(goi, &w);
3682 target->working_area_virt = w;
3683 target->working_area_virt_spec = true;
3685 if (goi->argc != 0) {
3689 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3693 case TCFG_WORK_AREA_PHYS:
3694 if (goi->isconfigure) {
3695 target_free_all_working_areas(target);
3696 e = Jim_GetOpt_Wide(goi, &w);
3700 target->working_area_phys = w;
3701 target->working_area_phys_spec = true;
3703 if (goi->argc != 0) {
3707 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3711 case TCFG_WORK_AREA_SIZE:
3712 if (goi->isconfigure) {
3713 target_free_all_working_areas(target);
3714 e = Jim_GetOpt_Wide(goi, &w);
3718 target->working_area_size = w;
3720 if (goi->argc != 0) {
3724 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3728 case TCFG_WORK_AREA_BACKUP:
3729 if (goi->isconfigure) {
3730 target_free_all_working_areas(target);
3731 e = Jim_GetOpt_Wide(goi, &w);
3735 /* make this exactly 1 or 0 */
3736 target->backup_working_area = (!!w);
3738 if (goi->argc != 0) {
3742 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3743 /* loop for more e*/
3747 if (goi->isconfigure) {
3748 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3750 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3753 target->endianness = n->value;
3755 if (goi->argc != 0) {
3759 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3760 if (n->name == NULL) {
3761 target->endianness = TARGET_LITTLE_ENDIAN;
3762 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3764 Jim_SetResultString(goi->interp, n->name, -1);
3769 if (goi->isconfigure) {
3770 if (goi->argc < 1) {
3771 Jim_SetResult_sprintf(goi->interp,
3776 if (target->variant) {
3777 free((void *)(target->variant));
3779 e = Jim_GetOpt_String(goi, &cp, NULL);
3780 target->variant = strdup(cp);
3782 if (goi->argc != 0) {
3786 Jim_SetResultString(goi->interp, target->variant,-1);
3789 case TCFG_CHAIN_POSITION:
3790 if (goi->isconfigure) {
3792 struct jtag_tap *tap;
3793 target_free_all_working_areas(target);
3794 e = Jim_GetOpt_Obj(goi, &o);
3798 tap = jtag_tap_by_jim_obj(goi->interp, o);
3802 /* make this exactly 1 or 0 */
3805 if (goi->argc != 0) {
3809 Jim_SetResultString(interp, target->tap->dotted_name, -1);
3810 /* loop for more e*/
3813 } /* while (goi->argc) */
3816 /* done - we return */
3820 /** this is the 'tcl' handler for the target specific command */
3821 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3826 uint8_t target_buf[32];
3828 struct target *target;
3829 struct command_context *cmd_ctx;
3836 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3837 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3838 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3839 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3847 TS_CMD_INVOKE_EVENT,
3850 static const Jim_Nvp target_options[] = {
3851 { .name = "configure", .value = TS_CMD_CONFIGURE },
3852 { .name = "cget", .value = TS_CMD_CGET },
3853 { .name = "mww", .value = TS_CMD_MWW },
3854 { .name = "mwh", .value = TS_CMD_MWH },
3855 { .name = "mwb", .value = TS_CMD_MWB },
3856 { .name = "mdw", .value = TS_CMD_MDW },
3857 { .name = "mdh", .value = TS_CMD_MDH },
3858 { .name = "mdb", .value = TS_CMD_MDB },
3859 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3860 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3861 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3862 { .name = "curstate", .value = TS_CMD_CURSTATE },
3864 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3865 { .name = "arp_poll", .value = TS_CMD_POLL },
3866 { .name = "arp_reset", .value = TS_CMD_RESET },
3867 { .name = "arp_halt", .value = TS_CMD_HALT },
3868 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3869 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3871 { .name = NULL, .value = -1 },
3874 /* go past the "command" */
3875 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3877 target = Jim_CmdPrivData(goi.interp);
3878 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3880 /* commands here are in an NVP table */
3881 e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3883 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3886 /* Assume blank result */
3887 Jim_SetEmptyResult(goi.interp);
3890 case TS_CMD_CONFIGURE:
3892 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3895 goi.isconfigure = 1;
3896 return target_configure(&goi, target);
3898 // some things take params
3900 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3903 goi.isconfigure = 0;
3904 return target_configure(&goi, target);
3912 * argv[3] = optional count.
3915 if ((goi.argc == 2) || (goi.argc == 3)) {
3919 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3923 e = Jim_GetOpt_Wide(&goi, &a);
3928 e = Jim_GetOpt_Wide(&goi, &b);
3932 if (goi.argc == 3) {
3933 e = Jim_GetOpt_Wide(&goi, &c);
3943 target_buffer_set_u32(target, target_buf, b);
3947 target_buffer_set_u16(target, target_buf, b);
3951 target_buffer_set_u8(target, target_buf, b);
3955 for (x = 0 ; x < c ; x++) {
3956 e = target_write_memory(target, a, b, 1, target_buf);
3957 if (e != ERROR_OK) {
3958 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3971 /* argv[0] = command
3973 * argv[2] = optional count
3975 if ((goi.argc == 2) || (goi.argc == 3)) {
3976 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3979 e = Jim_GetOpt_Wide(&goi, &a);
3984 e = Jim_GetOpt_Wide(&goi, &c);
3991 b = 1; /* shut up gcc */
4004 /* convert to "bytes" */
4006 /* count is now in 'BYTES' */
4012 e = target_read_memory(target, a, b, y / b, target_buf);
4013 if (e != ERROR_OK) {
4014 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4018 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4021 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
4022 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
4023 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4025 for (; (x < 16) ; x += 4) {
4026 Jim_fprintf(interp, interp->cookie_stdout, " ");
4030 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
4031 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
4032 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4034 for (; (x < 16) ; x += 2) {
4035 Jim_fprintf(interp, interp->cookie_stdout, " ");
4040 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4041 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4042 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4044 for (; (x < 16) ; x += 1) {
4045 Jim_fprintf(interp, interp->cookie_stdout, " ");
4049 /* ascii-ify the bytes */
4050 for (x = 0 ; x < y ; x++) {
4051 if ((target_buf[x] >= 0x20) &&
4052 (target_buf[x] <= 0x7e)) {
4056 target_buf[x] = '.';
4061 target_buf[x] = ' ';
4066 /* print - with a newline */
4067 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4073 case TS_CMD_MEM2ARRAY:
4074 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4076 case TS_CMD_ARRAY2MEM:
4077 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4079 case TS_CMD_EXAMINE:
4081 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4084 if (!target->tap->enabled)
4085 goto err_tap_disabled;
4086 e = target->type->examine(target);
4087 if (e != ERROR_OK) {
4088 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4094 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4097 if (!target->tap->enabled)
4098 goto err_tap_disabled;
4099 if (!(target_was_examined(target))) {
4100 e = ERROR_TARGET_NOT_EXAMINED;
4102 e = target->type->poll(target);
4104 if (e != ERROR_OK) {
4105 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4112 if (goi.argc != 2) {
4113 Jim_WrongNumArgs(interp, 2, argv,
4114 "([tT]|[fF]|assert|deassert) BOOL");
4117 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4119 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4122 /* the halt or not param */
4123 e = Jim_GetOpt_Wide(&goi, &a);
4127 if (!target->tap->enabled)
4128 goto err_tap_disabled;
4129 if (!target->type->assert_reset
4130 || !target->type->deassert_reset) {
4131 Jim_SetResult_sprintf(interp,
4132 "No target-specific reset for %s",
4136 /* determine if we should halt or not. */
4137 target->reset_halt = !!a;
4138 /* When this happens - all workareas are invalid. */
4139 target_free_all_working_areas_restore(target, 0);
4142 if (n->value == NVP_ASSERT) {
4143 e = target->type->assert_reset(target);
4145 e = target->type->deassert_reset(target);
4147 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4150 Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4153 if (!target->tap->enabled)
4154 goto err_tap_disabled;
4155 e = target->type->halt(target);
4156 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4157 case TS_CMD_WAITSTATE:
4158 /* params: <name> statename timeoutmsecs */
4159 if (goi.argc != 2) {
4160 Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4163 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4165 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4168 e = Jim_GetOpt_Wide(&goi, &a);
4172 if (!target->tap->enabled)
4173 goto err_tap_disabled;
4174 e = target_wait_state(target, n->value, a);
4175 if (e != ERROR_OK) {
4176 Jim_SetResult_sprintf(goi.interp,
4177 "target: %s wait %s fails (%d) %s",
4180 e, target_strerror_safe(e));
4185 case TS_CMD_EVENTLIST:
4186 /* List for human, Events defined for this target.
4187 * scripts/programs should use 'name cget -event NAME'
4190 struct target_event_action *teap;
4191 teap = target->event_action;
4192 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4193 target->target_number,
4195 command_print(cmd_ctx, "%-25s | Body", "Event");
4196 command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4198 command_print(cmd_ctx,
4200 Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4201 Jim_GetString(teap->body, NULL));
4204 command_print(cmd_ctx, "***END***");
4207 case TS_CMD_CURSTATE:
4208 if (goi.argc != 0) {
4209 Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4212 Jim_SetResultString(goi.interp,
4213 target_state_name( target ),
4216 case TS_CMD_INVOKE_EVENT:
4217 if (goi.argc != 1) {
4218 Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4221 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4223 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4226 target_handle_event(target, n->value);
4232 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4236 static int target_create(Jim_GetOptInfo *goi)
4244 struct target *target;
4245 struct command_context *cmd_ctx;
4247 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4248 if (goi->argc < 3) {
4249 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4254 Jim_GetOpt_Obj(goi, &new_cmd);
4255 /* does this command exist? */
4256 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4258 cp = Jim_GetString(new_cmd, NULL);
4259 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4264 e = Jim_GetOpt_String(goi, &cp2, NULL);
4266 /* now does target type exist */
4267 for (x = 0 ; target_types[x] ; x++) {
4268 if (0 == strcmp(cp, target_types[x]->name)) {
4273 if (target_types[x] == NULL) {
4274 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4275 for (x = 0 ; target_types[x] ; x++) {
4276 if (target_types[x + 1]) {
4277 Jim_AppendStrings(goi->interp,
4278 Jim_GetResult(goi->interp),
4279 target_types[x]->name,
4282 Jim_AppendStrings(goi->interp,
4283 Jim_GetResult(goi->interp),
4285 target_types[x]->name,NULL);
4292 target = calloc(1,sizeof(struct target));
4293 /* set target number */
4294 target->target_number = new_target_number();
4296 /* allocate memory for each unique target type */
4297 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4299 memcpy(target->type, target_types[x], sizeof(struct target_type));
4301 /* will be set by "-endian" */
4302 target->endianness = TARGET_ENDIAN_UNKNOWN;
4304 target->working_area = 0x0;
4305 target->working_area_size = 0x0;
4306 target->working_areas = NULL;
4307 target->backup_working_area = 0;
4309 target->state = TARGET_UNKNOWN;
4310 target->debug_reason = DBG_REASON_UNDEFINED;
4311 target->reg_cache = NULL;
4312 target->breakpoints = NULL;
4313 target->watchpoints = NULL;
4314 target->next = NULL;
4315 target->arch_info = NULL;
4317 target->display = 1;
4319 target->halt_issued = false;
4321 /* initialize trace information */
4322 target->trace_info = malloc(sizeof(struct trace));
4323 target->trace_info->num_trace_points = 0;
4324 target->trace_info->trace_points_size = 0;
4325 target->trace_info->trace_points = NULL;
4326 target->trace_info->trace_history_size = 0;
4327 target->trace_info->trace_history = NULL;
4328 target->trace_info->trace_history_pos = 0;
4329 target->trace_info->trace_history_overflowed = 0;
4331 target->dbgmsg = NULL;
4332 target->dbg_msg_enabled = 0;
4334 target->endianness = TARGET_ENDIAN_UNKNOWN;
4336 /* Do the rest as "configure" options */
4337 goi->isconfigure = 1;
4338 e = target_configure(goi, target);
4340 if (target->tap == NULL)
4342 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4352 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4353 /* default endian to little if not specified */
4354 target->endianness = TARGET_LITTLE_ENDIAN;
4357 /* incase variant is not set */
4358 if (!target->variant)
4359 target->variant = strdup("");
4361 /* create the target specific commands */
4362 if (target->type->register_commands) {
4363 (*(target->type->register_commands))(cmd_ctx);
4365 if (target->type->target_create) {
4366 (*(target->type->target_create))(target, goi->interp);
4369 /* append to end of list */
4371 struct target **tpp;
4372 tpp = &(all_targets);
4374 tpp = &((*tpp)->next);
4379 cp = Jim_GetString(new_cmd, NULL);
4380 target->cmd_name = strdup(cp);
4382 /* now - create the new target name command */
4383 e = Jim_CreateCommand(goi->interp,
4386 tcl_target_func, /* C function */
4387 target, /* private data */
4388 NULL); /* no del proc */
4393 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4397 struct command_context *cmd_ctx;
4398 struct target *target;
4401 /* TG = target generic */
4409 const char *target_cmds[] = {
4410 "create", "types", "names", "current", "number",
4412 NULL /* terminate */
4415 LOG_DEBUG("Target command params:");
4416 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4418 cmd_ctx = Jim_GetAssocData(interp, "context");
4420 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4422 if (goi.argc == 0) {
4423 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4427 /* Jim_GetOpt_Debug(&goi); */
4428 r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4435 Jim_Panic(goi.interp,"Why am I here?");
4437 case TG_CMD_CURRENT:
4438 if (goi.argc != 0) {
4439 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4442 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4445 if (goi.argc != 0) {
4446 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4449 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4450 for (x = 0 ; target_types[x] ; x++) {
4451 Jim_ListAppendElement(goi.interp,
4452 Jim_GetResult(goi.interp),
4453 Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4457 if (goi.argc != 0) {
4458 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4461 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4462 target = all_targets;
4464 Jim_ListAppendElement(goi.interp,
4465 Jim_GetResult(goi.interp),
4466 Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4467 target = target->next;
4472 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4475 return target_create(&goi);
4478 /* It's OK to remove this mechanism sometime after August 2010 or so */
4479 LOG_WARNING("don't use numbers as target identifiers; use names");
4480 if (goi.argc != 1) {
4481 Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4484 e = Jim_GetOpt_Wide(&goi, &w);
4488 for (x = 0, target = all_targets; target; target = target->next, x++) {
4489 if (target->target_number == w)
4492 if (target == NULL) {
4493 Jim_SetResult_sprintf(goi.interp,
4494 "Target: number %d does not exist", (int)(w));
4497 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4500 if (goi.argc != 0) {
4501 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4504 for (x = 0, target = all_targets; target; target = target->next, x++)
4506 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4522 static int fastload_num;
4523 static struct FastLoad *fastload;
4525 static void free_fastload(void)
4527 if (fastload != NULL)
4530 for (i = 0; i < fastload_num; i++)
4532 if (fastload[i].data)
4533 free(fastload[i].data);
4543 COMMAND_HANDLER(handle_fast_load_image_command)
4547 uint32_t image_size;
4548 uint32_t min_address = 0;
4549 uint32_t max_address = 0xffffffff;
4554 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_args,
4555 &image, &min_address, &max_address);
4556 if (ERROR_OK != retval)
4559 struct duration bench;
4560 duration_start(&bench);
4562 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4569 fastload_num = image.num_sections;
4570 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4571 if (fastload == NULL)
4573 image_close(&image);
4576 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4577 for (i = 0; i < image.num_sections; i++)
4579 buffer = malloc(image.sections[i].size);
4582 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4583 (int)(image.sections[i].size));
4587 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4593 uint32_t offset = 0;
4594 uint32_t length = buf_cnt;
4597 /* DANGER!!! beware of unsigned comparision here!!! */
4599 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4600 (image.sections[i].base_address < max_address))
4602 if (image.sections[i].base_address < min_address)
4604 /* clip addresses below */
4605 offset += min_address-image.sections[i].base_address;
4609 if (image.sections[i].base_address + buf_cnt > max_address)
4611 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4614 fastload[i].address = image.sections[i].base_address + offset;
4615 fastload[i].data = malloc(length);
4616 if (fastload[i].data == NULL)
4621 memcpy(fastload[i].data, buffer + offset, length);
4622 fastload[i].length = length;
4624 image_size += length;
4625 command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4626 (unsigned int)length,
4627 ((unsigned int)(image.sections[i].base_address + offset)));
4633 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4635 command_print(cmd_ctx, "Loaded %" PRIu32 " bytes "
4636 "in %fs (%0.3f kb/s)", image_size,
4637 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4639 command_print(cmd_ctx,
4640 "WARNING: image has not been loaded to target!"
4641 "You can issue a 'fast_load' to finish loading.");
4644 image_close(&image);
4646 if (retval != ERROR_OK)
4654 COMMAND_HANDLER(handle_fast_load_command)
4657 return ERROR_COMMAND_SYNTAX_ERROR;
4658 if (fastload == NULL)
4660 LOG_ERROR("No image in memory");
4664 int ms = timeval_ms();
4666 int retval = ERROR_OK;
4667 for (i = 0; i < fastload_num;i++)
4669 struct target *target = get_current_target(cmd_ctx);
4670 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4671 (unsigned int)(fastload[i].address),
4672 (unsigned int)(fastload[i].length));
4673 if (retval == ERROR_OK)
4675 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4677 size += fastload[i].length;
4679 int after = timeval_ms();
4680 command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4684 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4686 struct command_context *context;
4687 struct target *target;
4690 context = Jim_GetAssocData(interp, "context");
4691 if (context == NULL) {
4692 LOG_ERROR("array2mem: no command context");
4695 target = get_current_target(context);
4696 if (target == NULL) {
4697 LOG_ERROR("array2mem: no current target");
4701 if ((argc < 6) || (argc > 7))
4715 e = Jim_GetLong(interp, argv[1], &l);
4721 e = Jim_GetLong(interp, argv[2], &l);
4727 e = Jim_GetLong(interp, argv[3], &l);
4733 e = Jim_GetLong(interp, argv[4], &l);
4739 e = Jim_GetLong(interp, argv[5], &l);
4749 e = Jim_GetLong(interp, argv[6], &l);
4755 retval = target_mcr(target, cpnum, op1, op2, CRn, CRm, value);
4756 if (retval != ERROR_OK)
4760 retval = target_mrc(target, cpnum, op1, op2, CRn, CRm, &value);
4761 if (retval != ERROR_OK)
4764 Jim_SetResult(interp, Jim_NewIntObj(interp, value));
4770 int target_register_commands(struct command_context *cmd_ctx)
4773 register_command(cmd_ctx, NULL, "targets",
4774 handle_targets_command, COMMAND_EXEC,
4775 "change current command line target (one parameter) "
4776 "or list targets (no parameters)");
4778 register_jim(cmd_ctx, "target", jim_target, "configure target");
4783 int target_register_user_commands(struct command_context *cmd_ctx)
4785 int retval = ERROR_OK;
4786 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
4789 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
4792 register_command(cmd_ctx, NULL, "profile",
4793 handle_profile_command, COMMAND_EXEC,
4794 "profiling samples the CPU PC");
4796 register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array,
4797 "read memory and return as a TCL array for script processing "
4798 "<ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
4800 register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem,
4801 "convert a TCL array to memory locations and write the values "
4802 "<ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
4804 register_command(cmd_ctx, NULL, "fast_load_image",
4805 handle_fast_load_image_command, COMMAND_ANY,
4806 "same args as load_image, image stored in memory "
4807 "- mainly for profiling purposes");
4809 register_command(cmd_ctx, NULL, "fast_load",
4810 handle_fast_load_command, COMMAND_ANY,
4811 "loads active fast load image to current target "
4812 "- mainly for profiling purposes");
4814 /** @todo don't register virt2phys() unless target supports it */
4815 register_command(cmd_ctx, NULL, "virt2phys",
4816 handle_virt2phys_command, COMMAND_ANY,
4817 "translate a virtual address into a physical address");
4819 register_command(cmd_ctx, NULL, "reg",
4820 handle_reg_command, COMMAND_EXEC,
4821 "display or set a register");
4823 register_command(cmd_ctx, NULL, "poll",
4824 handle_poll_command, COMMAND_EXEC,
4825 "poll target state");
4826 register_command(cmd_ctx, NULL, "wait_halt",
4827 handle_wait_halt_command, COMMAND_EXEC,
4828 "wait for target halt [time (s)]");
4829 register_command(cmd_ctx, NULL, "halt",
4830 handle_halt_command, COMMAND_EXEC,
4832 register_command(cmd_ctx, NULL, "resume",
4833 handle_resume_command, COMMAND_EXEC,
4834 "resume target [addr]");
4835 register_command(cmd_ctx, NULL, "reset",
4836 handle_reset_command, COMMAND_EXEC,
4837 "reset target [run | halt | init] - default is run");
4838 register_command(cmd_ctx, NULL, "soft_reset_halt",
4839 handle_soft_reset_halt_command, COMMAND_EXEC,
4840 "halt the target and do a soft reset");
4842 register_command(cmd_ctx, NULL, "step",
4843 handle_step_command, COMMAND_EXEC,
4844 "step one instruction from current PC or [addr]");
4846 register_command(cmd_ctx, NULL, "mdw",
4847 handle_md_command, COMMAND_EXEC,
4848 "display memory words [phys] <addr> [count]");
4849 register_command(cmd_ctx, NULL, "mdh",
4850 handle_md_command, COMMAND_EXEC,
4851 "display memory half-words [phys] <addr> [count]");
4852 register_command(cmd_ctx, NULL, "mdb",
4853 handle_md_command, COMMAND_EXEC,
4854 "display memory bytes [phys] <addr> [count]");
4856 register_command(cmd_ctx, NULL, "mww",
4857 handle_mw_command, COMMAND_EXEC,
4858 "write memory word [phys] <addr> <value> [count]");
4859 register_command(cmd_ctx, NULL, "mwh",
4860 handle_mw_command, COMMAND_EXEC,
4861 "write memory half-word [phys] <addr> <value> [count]");
4862 register_command(cmd_ctx, NULL, "mwb",
4863 handle_mw_command, COMMAND_EXEC,
4864 "write memory byte [phys] <addr> <value> [count]");
4866 register_command(cmd_ctx, NULL, "bp",
4867 handle_bp_command, COMMAND_EXEC,
4868 "list or set breakpoint [<address> <length> [hw]]");
4869 register_command(cmd_ctx, NULL, "rbp",
4870 handle_rbp_command, COMMAND_EXEC,
4871 "remove breakpoint <address>");
4873 register_command(cmd_ctx, NULL, "wp",
4874 handle_wp_command, COMMAND_EXEC,
4875 "list or set watchpoint "
4876 "[<address> <length> <r/w/a> [value] [mask]]");
4877 register_command(cmd_ctx, NULL, "rwp",
4878 handle_rwp_command, COMMAND_EXEC,
4879 "remove watchpoint <address>");
4881 register_command(cmd_ctx, NULL, "load_image",
4882 handle_load_image_command, COMMAND_EXEC,
4883 "load_image <file> <address> "
4884 "['bin'|'ihex'|'elf'|'s19'] [min_address] [max_length]");
4885 register_command(cmd_ctx, NULL, "dump_image",
4886 handle_dump_image_command, COMMAND_EXEC,
4887 "dump_image <file> <address> <size>");
4888 register_command(cmd_ctx, NULL, "verify_image",
4889 handle_verify_image_command, COMMAND_EXEC,
4890 "verify_image <file> [offset] [type]");
4891 register_command(cmd_ctx, NULL, "test_image",
4892 handle_test_image_command, COMMAND_EXEC,
4893 "test_image <file> [offset] [type]");