1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2009 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
17 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program; if not, write to the *
29 * Free Software Foundation, Inc., *
30 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
31 ***************************************************************************/
37 #include "target_type.h"
38 #include "target_request.h"
39 #include "breakpoints.h"
40 #include "time_support.h"
47 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
49 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv);
50 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv);
53 extern struct target_type arm7tdmi_target;
54 extern struct target_type arm720t_target;
55 extern struct target_type arm9tdmi_target;
56 extern struct target_type arm920t_target;
57 extern struct target_type arm966e_target;
58 extern struct target_type arm926ejs_target;
59 extern struct target_type fa526_target;
60 extern struct target_type feroceon_target;
61 extern struct target_type dragonite_target;
62 extern struct target_type xscale_target;
63 extern struct target_type cortexm3_target;
64 extern struct target_type cortexa8_target;
65 extern struct target_type arm11_target;
66 extern struct target_type mips_m4k_target;
67 extern struct target_type avr_target;
68 extern struct target_type testee_target;
70 struct target_type *target_types[] =
91 struct target *all_targets = NULL;
92 struct target_event_callback *target_event_callbacks = NULL;
93 struct target_timer_callback *target_timer_callbacks = NULL;
95 const Jim_Nvp nvp_assert[] = {
96 { .name = "assert", NVP_ASSERT },
97 { .name = "deassert", NVP_DEASSERT },
98 { .name = "T", NVP_ASSERT },
99 { .name = "F", NVP_DEASSERT },
100 { .name = "t", NVP_ASSERT },
101 { .name = "f", NVP_DEASSERT },
102 { .name = NULL, .value = -1 }
105 const Jim_Nvp nvp_error_target[] = {
106 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
107 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
108 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
109 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
110 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
111 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
112 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
113 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
114 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
115 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
116 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
117 { .value = -1, .name = NULL }
120 const char *target_strerror_safe(int err)
124 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
125 if (n->name == NULL) {
132 static const Jim_Nvp nvp_target_event[] = {
133 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
134 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
136 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
137 { .value = TARGET_EVENT_HALTED, .name = "halted" },
138 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
139 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
140 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
142 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
143 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
145 /* historical name */
147 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
149 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
150 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
151 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
152 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
153 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
154 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
155 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
156 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
157 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
158 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
159 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
161 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
162 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
164 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
165 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
167 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
168 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
170 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
171 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
173 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
174 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
176 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
177 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
178 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
180 { .name = NULL, .value = -1 }
183 const Jim_Nvp nvp_target_state[] = {
184 { .name = "unknown", .value = TARGET_UNKNOWN },
185 { .name = "running", .value = TARGET_RUNNING },
186 { .name = "halted", .value = TARGET_HALTED },
187 { .name = "reset", .value = TARGET_RESET },
188 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
189 { .name = NULL, .value = -1 },
192 const Jim_Nvp nvp_target_debug_reason [] = {
193 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
194 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
195 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
196 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
197 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
198 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
199 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
200 { .name = NULL, .value = -1 },
203 const Jim_Nvp nvp_target_endian[] = {
204 { .name = "big", .value = TARGET_BIG_ENDIAN },
205 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
206 { .name = "be", .value = TARGET_BIG_ENDIAN },
207 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
208 { .name = NULL, .value = -1 },
211 const Jim_Nvp nvp_reset_modes[] = {
212 { .name = "unknown", .value = RESET_UNKNOWN },
213 { .name = "run" , .value = RESET_RUN },
214 { .name = "halt" , .value = RESET_HALT },
215 { .name = "init" , .value = RESET_INIT },
216 { .name = NULL , .value = -1 },
220 target_state_name( struct target *t )
223 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
225 LOG_ERROR("Invalid target state: %d", (int)(t->state));
226 cp = "(*BUG*unknown*BUG*)";
231 /* determine the number of the new target */
232 static int new_target_number(void)
237 /* number is 0 based */
241 if (x < t->target_number) {
242 x = t->target_number;
249 /* read a uint32_t from a buffer in target memory endianness */
250 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
252 if (target->endianness == TARGET_LITTLE_ENDIAN)
253 return le_to_h_u32(buffer);
255 return be_to_h_u32(buffer);
258 /* read a uint16_t from a buffer in target memory endianness */
259 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
261 if (target->endianness == TARGET_LITTLE_ENDIAN)
262 return le_to_h_u16(buffer);
264 return be_to_h_u16(buffer);
267 /* read a uint8_t from a buffer in target memory endianness */
268 uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
270 return *buffer & 0x0ff;
273 /* write a uint32_t to a buffer in target memory endianness */
274 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
276 if (target->endianness == TARGET_LITTLE_ENDIAN)
277 h_u32_to_le(buffer, value);
279 h_u32_to_be(buffer, value);
282 /* write a uint16_t to a buffer in target memory endianness */
283 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
285 if (target->endianness == TARGET_LITTLE_ENDIAN)
286 h_u16_to_le(buffer, value);
288 h_u16_to_be(buffer, value);
291 /* write a uint8_t to a buffer in target memory endianness */
292 void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
297 /* return a pointer to a configured target; id is name or number */
298 struct target *get_target(const char *id)
300 struct target *target;
302 /* try as tcltarget name */
303 for (target = all_targets; target; target = target->next) {
304 if (target->cmd_name == NULL)
306 if (strcmp(id, target->cmd_name) == 0)
310 /* It's OK to remove this fallback sometime after August 2010 or so */
312 /* no match, try as number */
314 if (parse_uint(id, &num) != ERROR_OK)
317 for (target = all_targets; target; target = target->next) {
318 if (target->target_number == (int)num) {
319 LOG_WARNING("use '%s' as target identifier, not '%u'",
320 target->cmd_name, num);
328 /* returns a pointer to the n-th configured target */
329 static struct target *get_target_by_num(int num)
331 struct target *target = all_targets;
334 if (target->target_number == num) {
337 target = target->next;
343 struct target* get_current_target(struct command_context *cmd_ctx)
345 struct target *target = get_target_by_num(cmd_ctx->current_target);
349 LOG_ERROR("BUG: current_target out of bounds");
356 int target_poll(struct target *target)
360 /* We can't poll until after examine */
361 if (!target_was_examined(target))
363 /* Fail silently lest we pollute the log */
367 retval = target->type->poll(target);
368 if (retval != ERROR_OK)
371 if (target->halt_issued)
373 if (target->state == TARGET_HALTED)
375 target->halt_issued = false;
378 long long t = timeval_ms() - target->halt_issued_time;
381 target->halt_issued = false;
382 LOG_INFO("Halt timed out, wake up GDB.");
383 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
391 int target_halt(struct target *target)
394 /* We can't poll until after examine */
395 if (!target_was_examined(target))
397 LOG_ERROR("Target not examined yet");
401 retval = target->type->halt(target);
402 if (retval != ERROR_OK)
405 target->halt_issued = true;
406 target->halt_issued_time = timeval_ms();
411 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
415 /* We can't poll until after examine */
416 if (!target_was_examined(target))
418 LOG_ERROR("Target not examined yet");
422 /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
423 * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
426 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
432 int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
437 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
438 if (n->name == NULL) {
439 LOG_ERROR("invalid reset mode");
443 /* disable polling during reset to make reset event scripts
444 * more predictable, i.e. dr/irscan & pathmove in events will
445 * not have JTAG operations injected into the middle of a sequence.
447 bool save_poll = jtag_poll_get_enabled();
449 jtag_poll_set_enabled(false);
451 sprintf(buf, "ocd_process_reset %s", n->name);
452 retval = Jim_Eval(interp, buf);
454 jtag_poll_set_enabled(save_poll);
456 if (retval != JIM_OK) {
457 Jim_PrintErrorMessage(interp);
461 /* We want any events to be processed before the prompt */
462 retval = target_call_timer_callbacks_now();
467 static int identity_virt2phys(struct target *target,
468 uint32_t virtual, uint32_t *physical)
474 static int no_mmu(struct target *target, int *enabled)
480 static int default_examine(struct target *target)
482 target_set_examined(target);
486 int target_examine_one(struct target *target)
488 return target->type->examine(target);
491 static int jtag_enable_callback(enum jtag_event event, void *priv)
493 struct target *target = priv;
495 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
498 jtag_unregister_event_callback(jtag_enable_callback, target);
499 return target_examine_one(target);
503 /* Targets that correctly implement init + examine, i.e.
504 * no communication with target during init:
508 int target_examine(void)
510 int retval = ERROR_OK;
511 struct target *target;
513 for (target = all_targets; target; target = target->next)
515 /* defer examination, but don't skip it */
516 if (!target->tap->enabled) {
517 jtag_register_event_callback(jtag_enable_callback,
521 if ((retval = target_examine_one(target)) != ERROR_OK)
526 const char *target_type_name(struct target *target)
528 return target->type->name;
531 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
533 if (!target_was_examined(target))
535 LOG_ERROR("Target not examined yet");
538 return target->type->write_memory_imp(target, address, size, count, buffer);
541 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
543 if (!target_was_examined(target))
545 LOG_ERROR("Target not examined yet");
548 return target->type->read_memory_imp(target, address, size, count, buffer);
551 static int target_soft_reset_halt_imp(struct target *target)
553 if (!target_was_examined(target))
555 LOG_ERROR("Target not examined yet");
558 if (!target->type->soft_reset_halt_imp) {
559 LOG_ERROR("Target %s does not support soft_reset_halt",
560 target_name(target));
563 return target->type->soft_reset_halt_imp(target);
566 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)
568 if (!target_was_examined(target))
570 LOG_ERROR("Target not examined yet");
573 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);
576 int target_read_memory(struct target *target,
577 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
579 return target->type->read_memory(target, address, size, count, buffer);
582 int target_read_phys_memory(struct target *target,
583 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
585 return target->type->read_phys_memory(target, address, size, count, buffer);
588 int target_write_memory(struct target *target,
589 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
591 return target->type->write_memory(target, address, size, count, buffer);
594 int target_write_phys_memory(struct target *target,
595 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
597 return target->type->write_phys_memory(target, address, size, count, buffer);
600 int target_bulk_write_memory(struct target *target,
601 uint32_t address, uint32_t count, uint8_t *buffer)
603 return target->type->bulk_write_memory(target, address, count, buffer);
606 int target_add_breakpoint(struct target *target,
607 struct breakpoint *breakpoint)
609 return target->type->add_breakpoint(target, breakpoint);
611 int target_remove_breakpoint(struct target *target,
612 struct breakpoint *breakpoint)
614 return target->type->remove_breakpoint(target, breakpoint);
617 int target_add_watchpoint(struct target *target,
618 struct watchpoint *watchpoint)
620 return target->type->add_watchpoint(target, watchpoint);
622 int target_remove_watchpoint(struct target *target,
623 struct watchpoint *watchpoint)
625 return target->type->remove_watchpoint(target, watchpoint);
628 int target_get_gdb_reg_list(struct target *target,
629 struct reg **reg_list[], int *reg_list_size)
631 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
633 int target_step(struct target *target,
634 int current, uint32_t address, int handle_breakpoints)
636 return target->type->step(target, current, address, handle_breakpoints);
640 int target_run_algorithm(struct target *target,
641 int num_mem_params, struct mem_param *mem_params,
642 int num_reg_params, struct reg_param *reg_param,
643 uint32_t entry_point, uint32_t exit_point,
644 int timeout_ms, void *arch_info)
646 return target->type->run_algorithm(target,
647 num_mem_params, mem_params, num_reg_params, reg_param,
648 entry_point, exit_point, timeout_ms, arch_info);
652 * Reset the @c examined flag for the given target.
653 * Pure paranoia -- targets are zeroed on allocation.
655 static void target_reset_examined(struct target *target)
657 target->examined = false;
662 static int default_mrc(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
664 LOG_ERROR("Not implemented: %s", __func__);
668 static int default_mcr(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
670 LOG_ERROR("Not implemented: %s", __func__);
674 static int arm_cp_check(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm)
677 if (!target_was_examined(target))
679 LOG_ERROR("Target not examined yet");
683 if ((cpnum <0) || (cpnum > 15))
685 LOG_ERROR("Illegal co-processor %d", cpnum);
691 LOG_ERROR("Illegal op1");
697 LOG_ERROR("Illegal op2");
703 LOG_ERROR("Illegal CRn");
709 LOG_ERROR("Illegal CRm");
716 int target_mrc(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
720 retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
721 if (retval != ERROR_OK)
724 return target->type->mrc(target, cpnum, op1, op2, CRn, CRm, value);
727 int target_mcr(struct target *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
731 retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
732 if (retval != ERROR_OK)
735 return target->type->mcr(target, cpnum, op1, op2, CRn, CRm, value);
739 err_read_phys_memory(struct target *target, uint32_t address,
740 uint32_t size, uint32_t count, uint8_t *buffer)
742 LOG_ERROR("Not implemented: %s", __func__);
747 err_write_phys_memory(struct target *target, uint32_t address,
748 uint32_t size, uint32_t count, uint8_t *buffer)
750 LOG_ERROR("Not implemented: %s", __func__);
754 int target_init(struct command_context *cmd_ctx)
756 struct target *target;
759 for (target = all_targets; target; target = target->next) {
760 struct target_type *type = target->type;
762 target_reset_examined(target);
763 if (target->type->examine == NULL)
765 target->type->examine = default_examine;
768 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
770 LOG_ERROR("target '%s' init failed", target_name(target));
775 * @todo MCR/MRC are ARM-specific; don't require them in
776 * all targets, or for ARMs without coprocessors.
778 if (target->type->mcr == NULL)
780 target->type->mcr = default_mcr;
783 const struct command_registration mcr_cmd = {
785 .mode = COMMAND_EXEC,
786 .jim_handler = &jim_mcrmrc,
787 .help = "write coprocessor",
788 .usage = "<cpnum> <op1> <op2> <CRn> <CRm> <value>",
790 register_command(cmd_ctx, NULL, &mcr_cmd);
793 if (target->type->mrc == NULL)
795 target->type->mrc = default_mrc;
798 const struct command_registration mrc_cmd = {
800 .jim_handler = &jim_mcrmrc,
801 .help = "read coprocessor",
802 .usage = "<cpnum> <op1> <op2> <CRn> <CRm>",
804 register_command(cmd_ctx, NULL, &mrc_cmd);
809 * @todo get rid of those *memory_imp() methods, now that all
810 * callers are using target_*_memory() accessors ... and make
811 * sure the "physical" paths handle the same issues.
814 /* a non-invasive way(in terms of patches) to add some code that
815 * runs before the type->write/read_memory implementation
817 target->type->write_memory_imp = target->type->write_memory;
818 target->type->write_memory = target_write_memory_imp;
819 target->type->read_memory_imp = target->type->read_memory;
820 target->type->read_memory = target_read_memory_imp;
821 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
822 target->type->soft_reset_halt = target_soft_reset_halt_imp;
823 target->type->run_algorithm_imp = target->type->run_algorithm;
824 target->type->run_algorithm = target_run_algorithm_imp;
826 /* Sanity-check MMU support ... stub in what we must, to help
827 * implement it in stages, but warn if we need to do so.
830 if (type->write_phys_memory == NULL) {
831 LOG_ERROR("type '%s' is missing %s",
833 "write_phys_memory");
834 type->write_phys_memory = err_write_phys_memory;
836 if (type->read_phys_memory == NULL) {
837 LOG_ERROR("type '%s' is missing %s",
840 type->read_phys_memory = err_read_phys_memory;
842 if (type->virt2phys == NULL) {
843 LOG_ERROR("type '%s' is missing %s",
846 type->virt2phys = identity_virt2phys;
849 /* Make sure no-MMU targets all behave the same: make no
850 * distinction between physical and virtual addresses, and
851 * ensure that virt2phys() is always an identity mapping.
854 if (type->write_phys_memory
855 || type->read_phys_memory
857 LOG_WARNING("type '%s' has broken MMU hooks",
861 type->write_phys_memory = type->write_memory;
862 type->read_phys_memory = type->read_memory;
863 type->virt2phys = identity_virt2phys;
869 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
871 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
878 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
880 struct target_event_callback **callbacks_p = &target_event_callbacks;
882 if (callback == NULL)
884 return ERROR_INVALID_ARGUMENTS;
889 while ((*callbacks_p)->next)
890 callbacks_p = &((*callbacks_p)->next);
891 callbacks_p = &((*callbacks_p)->next);
894 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
895 (*callbacks_p)->callback = callback;
896 (*callbacks_p)->priv = priv;
897 (*callbacks_p)->next = NULL;
902 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
904 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
907 if (callback == NULL)
909 return ERROR_INVALID_ARGUMENTS;
914 while ((*callbacks_p)->next)
915 callbacks_p = &((*callbacks_p)->next);
916 callbacks_p = &((*callbacks_p)->next);
919 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
920 (*callbacks_p)->callback = callback;
921 (*callbacks_p)->periodic = periodic;
922 (*callbacks_p)->time_ms = time_ms;
924 gettimeofday(&now, NULL);
925 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
926 time_ms -= (time_ms % 1000);
927 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
928 if ((*callbacks_p)->when.tv_usec > 1000000)
930 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
931 (*callbacks_p)->when.tv_sec += 1;
934 (*callbacks_p)->priv = priv;
935 (*callbacks_p)->next = NULL;
940 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
942 struct target_event_callback **p = &target_event_callbacks;
943 struct target_event_callback *c = target_event_callbacks;
945 if (callback == NULL)
947 return ERROR_INVALID_ARGUMENTS;
952 struct target_event_callback *next = c->next;
953 if ((c->callback == callback) && (c->priv == priv))
967 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
969 struct target_timer_callback **p = &target_timer_callbacks;
970 struct target_timer_callback *c = target_timer_callbacks;
972 if (callback == NULL)
974 return ERROR_INVALID_ARGUMENTS;
979 struct target_timer_callback *next = c->next;
980 if ((c->callback == callback) && (c->priv == priv))
994 int target_call_event_callbacks(struct target *target, enum target_event event)
996 struct target_event_callback *callback = target_event_callbacks;
997 struct target_event_callback *next_callback;
999 if (event == TARGET_EVENT_HALTED)
1001 /* execute early halted first */
1002 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1005 LOG_DEBUG("target event %i (%s)",
1007 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1009 target_handle_event(target, event);
1013 next_callback = callback->next;
1014 callback->callback(target, event, callback->priv);
1015 callback = next_callback;
1021 static int target_timer_callback_periodic_restart(
1022 struct target_timer_callback *cb, struct timeval *now)
1024 int time_ms = cb->time_ms;
1025 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1026 time_ms -= (time_ms % 1000);
1027 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1028 if (cb->when.tv_usec > 1000000)
1030 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1031 cb->when.tv_sec += 1;
1036 static int target_call_timer_callback(struct target_timer_callback *cb,
1037 struct timeval *now)
1039 cb->callback(cb->priv);
1042 return target_timer_callback_periodic_restart(cb, now);
1044 return target_unregister_timer_callback(cb->callback, cb->priv);
1047 static int target_call_timer_callbacks_check_time(int checktime)
1052 gettimeofday(&now, NULL);
1054 struct target_timer_callback *callback = target_timer_callbacks;
1057 // cleaning up may unregister and free this callback
1058 struct target_timer_callback *next_callback = callback->next;
1060 bool call_it = callback->callback &&
1061 ((!checktime && callback->periodic) ||
1062 now.tv_sec > callback->when.tv_sec ||
1063 (now.tv_sec == callback->when.tv_sec &&
1064 now.tv_usec >= callback->when.tv_usec));
1068 int retval = target_call_timer_callback(callback, &now);
1069 if (retval != ERROR_OK)
1073 callback = next_callback;
1079 int target_call_timer_callbacks(void)
1081 return target_call_timer_callbacks_check_time(1);
1084 /* invoke periodic callbacks immediately */
1085 int target_call_timer_callbacks_now(void)
1087 return target_call_timer_callbacks_check_time(0);
1090 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1092 struct working_area *c = target->working_areas;
1093 struct working_area *new_wa = NULL;
1095 /* Reevaluate working area address based on MMU state*/
1096 if (target->working_areas == NULL)
1101 retval = target->type->mmu(target, &enabled);
1102 if (retval != ERROR_OK)
1108 if (target->working_area_phys_spec) {
1109 LOG_DEBUG("MMU disabled, using physical "
1110 "address for working memory 0x%08x",
1111 (unsigned)target->working_area_phys);
1112 target->working_area = target->working_area_phys;
1114 LOG_ERROR("No working memory available. "
1115 "Specify -work-area-phys to target.");
1116 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1119 if (target->working_area_virt_spec) {
1120 LOG_DEBUG("MMU enabled, using virtual "
1121 "address for working memory 0x%08x",
1122 (unsigned)target->working_area_virt);
1123 target->working_area = target->working_area_virt;
1125 LOG_ERROR("No working memory available. "
1126 "Specify -work-area-virt to target.");
1127 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1132 /* only allocate multiples of 4 byte */
1135 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1136 size = (size + 3) & (~3);
1139 /* see if there's already a matching working area */
1142 if ((c->free) && (c->size == size))
1150 /* if not, allocate a new one */
1153 struct working_area **p = &target->working_areas;
1154 uint32_t first_free = target->working_area;
1155 uint32_t free_size = target->working_area_size;
1157 c = target->working_areas;
1160 first_free += c->size;
1161 free_size -= c->size;
1166 if (free_size < size)
1168 LOG_WARNING("not enough working area available(requested %u, free %u)",
1169 (unsigned)(size), (unsigned)(free_size));
1170 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1173 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1175 new_wa = malloc(sizeof(struct working_area));
1176 new_wa->next = NULL;
1177 new_wa->size = size;
1178 new_wa->address = first_free;
1180 if (target->backup_working_area)
1183 new_wa->backup = malloc(new_wa->size);
1184 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1186 free(new_wa->backup);
1193 new_wa->backup = NULL;
1196 /* put new entry in list */
1200 /* mark as used, and return the new (reused) area */
1205 new_wa->user = area;
1210 int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1215 if (restore && target->backup_working_area)
1218 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1224 /* mark user pointer invalid */
1231 int target_free_working_area(struct target *target, struct working_area *area)
1233 return target_free_working_area_restore(target, area, 1);
1236 /* free resources and restore memory, if restoring memory fails,
1237 * free up resources anyway
1239 void target_free_all_working_areas_restore(struct target *target, int restore)
1241 struct working_area *c = target->working_areas;
1245 struct working_area *next = c->next;
1246 target_free_working_area_restore(target, c, restore);
1256 target->working_areas = NULL;
1259 void target_free_all_working_areas(struct target *target)
1261 target_free_all_working_areas_restore(target, 1);
1264 int target_arch_state(struct target *target)
1269 LOG_USER("No target has been configured");
1273 LOG_USER("target state: %s", target_state_name( target ));
1275 if (target->state != TARGET_HALTED)
1278 retval = target->type->arch_state(target);
1282 /* Single aligned words are guaranteed to use 16 or 32 bit access
1283 * mode respectively, otherwise data is handled as quickly as
1286 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1289 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1290 (int)size, (unsigned)address);
1292 if (!target_was_examined(target))
1294 LOG_ERROR("Target not examined yet");
1302 if ((address + size - 1) < address)
1304 /* GDB can request this when e.g. PC is 0xfffffffc*/
1305 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1311 if (((address % 2) == 0) && (size == 2))
1313 return target_write_memory(target, address, 2, 1, buffer);
1316 /* handle unaligned head bytes */
1319 uint32_t unaligned = 4 - (address % 4);
1321 if (unaligned > size)
1324 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1327 buffer += unaligned;
1328 address += unaligned;
1332 /* handle aligned words */
1335 int aligned = size - (size % 4);
1337 /* use bulk writes above a certain limit. This may have to be changed */
1340 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1345 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1354 /* handle tail writes of less than 4 bytes */
1357 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1364 /* Single aligned words are guaranteed to use 16 or 32 bit access
1365 * mode respectively, otherwise data is handled as quickly as
1368 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1371 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1372 (int)size, (unsigned)address);
1374 if (!target_was_examined(target))
1376 LOG_ERROR("Target not examined yet");
1384 if ((address + size - 1) < address)
1386 /* GDB can request this when e.g. PC is 0xfffffffc*/
1387 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1393 if (((address % 2) == 0) && (size == 2))
1395 return target_read_memory(target, address, 2, 1, buffer);
1398 /* handle unaligned head bytes */
1401 uint32_t unaligned = 4 - (address % 4);
1403 if (unaligned > size)
1406 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1409 buffer += unaligned;
1410 address += unaligned;
1414 /* handle aligned words */
1417 int aligned = size - (size % 4);
1419 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1427 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1430 int aligned = size - (size%2);
1431 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1432 if (retval != ERROR_OK)
1439 /* handle tail writes of less than 4 bytes */
1442 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1449 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1454 uint32_t checksum = 0;
1455 if (!target_was_examined(target))
1457 LOG_ERROR("Target not examined yet");
1461 if ((retval = target->type->checksum_memory(target, address,
1462 size, &checksum)) != ERROR_OK)
1464 buffer = malloc(size);
1467 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1468 return ERROR_INVALID_ARGUMENTS;
1470 retval = target_read_buffer(target, address, size, buffer);
1471 if (retval != ERROR_OK)
1477 /* convert to target endianess */
1478 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1480 uint32_t target_data;
1481 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1482 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1485 retval = image_calculate_checksum(buffer, size, &checksum);
1494 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1497 if (!target_was_examined(target))
1499 LOG_ERROR("Target not examined yet");
1503 if (target->type->blank_check_memory == 0)
1504 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1506 retval = target->type->blank_check_memory(target, address, size, blank);
1511 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1513 uint8_t value_buf[4];
1514 if (!target_was_examined(target))
1516 LOG_ERROR("Target not examined yet");
1520 int retval = target_read_memory(target, address, 4, 1, value_buf);
1522 if (retval == ERROR_OK)
1524 *value = target_buffer_get_u32(target, value_buf);
1525 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1532 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1539 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1541 uint8_t value_buf[2];
1542 if (!target_was_examined(target))
1544 LOG_ERROR("Target not examined yet");
1548 int retval = target_read_memory(target, address, 2, 1, value_buf);
1550 if (retval == ERROR_OK)
1552 *value = target_buffer_get_u16(target, value_buf);
1553 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1560 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1567 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1569 int retval = target_read_memory(target, address, 1, 1, value);
1570 if (!target_was_examined(target))
1572 LOG_ERROR("Target not examined yet");
1576 if (retval == ERROR_OK)
1578 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1585 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1592 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1595 uint8_t value_buf[4];
1596 if (!target_was_examined(target))
1598 LOG_ERROR("Target not examined yet");
1602 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1606 target_buffer_set_u32(target, value_buf, value);
1607 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1609 LOG_DEBUG("failed: %i", retval);
1615 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1618 uint8_t value_buf[2];
1619 if (!target_was_examined(target))
1621 LOG_ERROR("Target not examined yet");
1625 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1629 target_buffer_set_u16(target, value_buf, value);
1630 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1632 LOG_DEBUG("failed: %i", retval);
1638 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1641 if (!target_was_examined(target))
1643 LOG_ERROR("Target not examined yet");
1647 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1650 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1652 LOG_DEBUG("failed: %i", retval);
1658 COMMAND_HANDLER(handle_targets_command)
1660 struct target *target = all_targets;
1664 target = get_target(CMD_ARGV[0]);
1665 if (target == NULL) {
1666 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1669 if (!target->tap->enabled) {
1670 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1671 "can't be the current target\n",
1672 target->tap->dotted_name);
1676 CMD_CTX->current_target = target->target_number;
1681 target = all_targets;
1682 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1683 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1689 if (target->tap->enabled)
1690 state = target_state_name( target );
1692 state = "tap-disabled";
1694 if (CMD_CTX->current_target == target->target_number)
1697 /* keep columns lined up to match the headers above */
1698 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1699 target->target_number,
1701 target_name(target),
1702 target_type_name(target),
1703 Jim_Nvp_value2name_simple(nvp_target_endian,
1704 target->endianness)->name,
1705 target->tap->dotted_name,
1707 target = target->next;
1713 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1715 static int powerDropout;
1716 static int srstAsserted;
1718 static int runPowerRestore;
1719 static int runPowerDropout;
1720 static int runSrstAsserted;
1721 static int runSrstDeasserted;
1723 static int sense_handler(void)
1725 static int prevSrstAsserted = 0;
1726 static int prevPowerdropout = 0;
1729 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1733 powerRestored = prevPowerdropout && !powerDropout;
1736 runPowerRestore = 1;
1739 long long current = timeval_ms();
1740 static long long lastPower = 0;
1741 int waitMore = lastPower + 2000 > current;
1742 if (powerDropout && !waitMore)
1744 runPowerDropout = 1;
1745 lastPower = current;
1748 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1752 srstDeasserted = prevSrstAsserted && !srstAsserted;
1754 static long long lastSrst = 0;
1755 waitMore = lastSrst + 2000 > current;
1756 if (srstDeasserted && !waitMore)
1758 runSrstDeasserted = 1;
1762 if (!prevSrstAsserted && srstAsserted)
1764 runSrstAsserted = 1;
1767 prevSrstAsserted = srstAsserted;
1768 prevPowerdropout = powerDropout;
1770 if (srstDeasserted || powerRestored)
1772 /* Other than logging the event we can't do anything here.
1773 * Issuing a reset is a particularly bad idea as we might
1774 * be inside a reset already.
1781 static void target_call_event_callbacks_all(enum target_event e) {
1782 struct target *target;
1783 target = all_targets;
1785 target_call_event_callbacks(target, e);
1786 target = target->next;
1790 /* process target state changes */
1791 int handle_target(void *priv)
1793 int retval = ERROR_OK;
1795 /* we do not want to recurse here... */
1796 static int recursive = 0;
1801 /* danger! running these procedures can trigger srst assertions and power dropouts.
1802 * We need to avoid an infinite loop/recursion here and we do that by
1803 * clearing the flags after running these events.
1805 int did_something = 0;
1806 if (runSrstAsserted)
1808 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1809 Jim_Eval(interp, "srst_asserted");
1812 if (runSrstDeasserted)
1814 Jim_Eval(interp, "srst_deasserted");
1817 if (runPowerDropout)
1819 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1820 Jim_Eval(interp, "power_dropout");
1823 if (runPowerRestore)
1825 Jim_Eval(interp, "power_restore");
1831 /* clear detect flags */
1835 /* clear action flags */
1837 runSrstAsserted = 0;
1838 runSrstDeasserted = 0;
1839 runPowerRestore = 0;
1840 runPowerDropout = 0;
1845 /* Poll targets for state changes unless that's globally disabled.
1846 * Skip targets that are currently disabled.
1848 for (struct target *target = all_targets;
1849 is_jtag_poll_safe() && target;
1850 target = target->next)
1852 if (!target->tap->enabled)
1855 /* only poll target if we've got power and srst isn't asserted */
1856 if (!powerDropout && !srstAsserted)
1858 /* polling may fail silently until the target has been examined */
1859 if ((retval = target_poll(target)) != ERROR_OK)
1861 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1870 COMMAND_HANDLER(handle_reg_command)
1872 struct target *target;
1873 struct reg *reg = NULL;
1879 target = get_current_target(CMD_CTX);
1881 /* list all available registers for the current target */
1884 struct reg_cache *cache = target->reg_cache;
1891 command_print(CMD_CTX, "===== %s", cache->name);
1893 for (i = 0, reg = cache->reg_list;
1894 i < cache->num_regs;
1895 i++, reg++, count++)
1897 /* only print cached values if they are valid */
1899 value = buf_to_str(reg->value,
1901 command_print(CMD_CTX,
1902 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1910 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1915 cache = cache->next;
1921 /* access a single register by its ordinal number */
1922 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1925 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1927 struct reg_cache *cache = target->reg_cache;
1932 for (i = 0; i < cache->num_regs; i++)
1936 reg = &cache->reg_list[i];
1942 cache = cache->next;
1947 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1950 } else /* access a single register by its name */
1952 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
1956 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
1961 /* display a register */
1962 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
1964 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
1967 if (reg->valid == 0)
1969 reg->type->get(reg);
1971 value = buf_to_str(reg->value, reg->size, 16);
1972 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1977 /* set register value */
1980 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
1981 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
1983 reg->type->set(reg, buf);
1985 value = buf_to_str(reg->value, reg->size, 16);
1986 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1994 command_print(CMD_CTX, "usage: reg <#|name> [value]");
1999 COMMAND_HANDLER(handle_poll_command)
2001 int retval = ERROR_OK;
2002 struct target *target = get_current_target(CMD_CTX);
2006 command_print(CMD_CTX, "background polling: %s",
2007 jtag_poll_get_enabled() ? "on" : "off");
2008 command_print(CMD_CTX, "TAP: %s (%s)",
2009 target->tap->dotted_name,
2010 target->tap->enabled ? "enabled" : "disabled");
2011 if (!target->tap->enabled)
2013 if ((retval = target_poll(target)) != ERROR_OK)
2015 if ((retval = target_arch_state(target)) != ERROR_OK)
2018 else if (CMD_ARGC == 1)
2021 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2022 jtag_poll_set_enabled(enable);
2026 return ERROR_COMMAND_SYNTAX_ERROR;
2032 COMMAND_HANDLER(handle_wait_halt_command)
2035 return ERROR_COMMAND_SYNTAX_ERROR;
2040 int retval = parse_uint(CMD_ARGV[0], &ms);
2041 if (ERROR_OK != retval)
2043 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2044 return ERROR_COMMAND_SYNTAX_ERROR;
2046 // convert seconds (given) to milliseconds (needed)
2050 struct target *target = get_current_target(CMD_CTX);
2051 return target_wait_state(target, TARGET_HALTED, ms);
2054 /* wait for target state to change. The trick here is to have a low
2055 * latency for short waits and not to suck up all the CPU time
2058 * After 500ms, keep_alive() is invoked
2060 int target_wait_state(struct target *target, enum target_state state, int ms)
2063 long long then = 0, cur;
2068 if ((retval = target_poll(target)) != ERROR_OK)
2070 if (target->state == state)
2078 then = timeval_ms();
2079 LOG_DEBUG("waiting for target %s...",
2080 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2088 if ((cur-then) > ms)
2090 LOG_ERROR("timed out while waiting for target %s",
2091 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2099 COMMAND_HANDLER(handle_halt_command)
2103 struct target *target = get_current_target(CMD_CTX);
2104 int retval = target_halt(target);
2105 if (ERROR_OK != retval)
2111 retval = parse_uint(CMD_ARGV[0], &wait);
2112 if (ERROR_OK != retval)
2113 return ERROR_COMMAND_SYNTAX_ERROR;
2118 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2121 COMMAND_HANDLER(handle_soft_reset_halt_command)
2123 struct target *target = get_current_target(CMD_CTX);
2125 LOG_USER("requesting target halt and executing a soft reset");
2127 target->type->soft_reset_halt(target);
2132 COMMAND_HANDLER(handle_reset_command)
2135 return ERROR_COMMAND_SYNTAX_ERROR;
2137 enum target_reset_mode reset_mode = RESET_RUN;
2141 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2142 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2143 return ERROR_COMMAND_SYNTAX_ERROR;
2145 reset_mode = n->value;
2148 /* reset *all* targets */
2149 return target_process_reset(CMD_CTX, reset_mode);
2153 COMMAND_HANDLER(handle_resume_command)
2157 return ERROR_COMMAND_SYNTAX_ERROR;
2159 struct target *target = get_current_target(CMD_CTX);
2160 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2162 /* with no CMD_ARGV, resume from current pc, addr = 0,
2163 * with one arguments, addr = CMD_ARGV[0],
2164 * handle breakpoints, not debugging */
2168 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2172 return target_resume(target, current, addr, 1, 0);
2175 COMMAND_HANDLER(handle_step_command)
2178 return ERROR_COMMAND_SYNTAX_ERROR;
2182 /* with no CMD_ARGV, step from current pc, addr = 0,
2183 * with one argument addr = CMD_ARGV[0],
2184 * handle breakpoints, debugging */
2189 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2193 struct target *target = get_current_target(CMD_CTX);
2195 return target->type->step(target, current_pc, addr, 1);
2198 static void handle_md_output(struct command_context *cmd_ctx,
2199 struct target *target, uint32_t address, unsigned size,
2200 unsigned count, const uint8_t *buffer)
2202 const unsigned line_bytecnt = 32;
2203 unsigned line_modulo = line_bytecnt / size;
2205 char output[line_bytecnt * 4 + 1];
2206 unsigned output_len = 0;
2208 const char *value_fmt;
2210 case 4: value_fmt = "%8.8x "; break;
2211 case 2: value_fmt = "%4.2x "; break;
2212 case 1: value_fmt = "%2.2x "; break;
2214 LOG_ERROR("invalid memory read size: %u", size);
2218 for (unsigned i = 0; i < count; i++)
2220 if (i % line_modulo == 0)
2222 output_len += snprintf(output + output_len,
2223 sizeof(output) - output_len,
2225 (unsigned)(address + (i*size)));
2229 const uint8_t *value_ptr = buffer + i * size;
2231 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2232 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2233 case 1: value = *value_ptr;
2235 output_len += snprintf(output + output_len,
2236 sizeof(output) - output_len,
2239 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2241 command_print(cmd_ctx, "%s", output);
2247 COMMAND_HANDLER(handle_md_command)
2250 return ERROR_COMMAND_SYNTAX_ERROR;
2253 switch (CMD_NAME[2]) {
2254 case 'w': size = 4; break;
2255 case 'h': size = 2; break;
2256 case 'b': size = 1; break;
2257 default: return ERROR_COMMAND_SYNTAX_ERROR;
2260 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2261 int (*fn)(struct target *target,
2262 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2267 fn=target_read_phys_memory;
2270 fn=target_read_memory;
2272 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2274 return ERROR_COMMAND_SYNTAX_ERROR;
2278 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2282 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2284 uint8_t *buffer = calloc(count, size);
2286 struct target *target = get_current_target(CMD_CTX);
2287 int retval = fn(target, address, size, count, buffer);
2288 if (ERROR_OK == retval)
2289 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2296 COMMAND_HANDLER(handle_mw_command)
2300 return ERROR_COMMAND_SYNTAX_ERROR;
2302 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2303 int (*fn)(struct target *target,
2304 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2309 fn=target_write_phys_memory;
2312 fn=target_write_memory;
2314 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2315 return ERROR_COMMAND_SYNTAX_ERROR;
2318 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2321 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2325 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2327 struct target *target = get_current_target(CMD_CTX);
2329 uint8_t value_buf[4];
2330 switch (CMD_NAME[2])
2334 target_buffer_set_u32(target, value_buf, value);
2338 target_buffer_set_u16(target, value_buf, value);
2342 value_buf[0] = value;
2345 return ERROR_COMMAND_SYNTAX_ERROR;
2347 for (unsigned i = 0; i < count; i++)
2349 int retval = fn(target,
2350 address + i * wordsize, wordsize, 1, value_buf);
2351 if (ERROR_OK != retval)
2360 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2361 uint32_t *min_address, uint32_t *max_address)
2363 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2364 return ERROR_COMMAND_SYNTAX_ERROR;
2366 /* a base address isn't always necessary,
2367 * default to 0x0 (i.e. don't relocate) */
2371 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2372 image->base_address = addr;
2373 image->base_address_set = 1;
2376 image->base_address_set = 0;
2378 image->start_address_set = 0;
2382 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2386 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2387 // use size (given) to find max (required)
2388 *max_address += *min_address;
2391 if (*min_address > *max_address)
2392 return ERROR_COMMAND_SYNTAX_ERROR;
2397 COMMAND_HANDLER(handle_load_image_command)
2401 uint32_t image_size;
2402 uint32_t min_address = 0;
2403 uint32_t max_address = 0xffffffff;
2407 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2408 &image, &min_address, &max_address);
2409 if (ERROR_OK != retval)
2412 struct target *target = get_current_target(CMD_CTX);
2414 struct duration bench;
2415 duration_start(&bench);
2417 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2424 for (i = 0; i < image.num_sections; i++)
2426 buffer = malloc(image.sections[i].size);
2429 command_print(CMD_CTX,
2430 "error allocating buffer for section (%d bytes)",
2431 (int)(image.sections[i].size));
2435 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2441 uint32_t offset = 0;
2442 uint32_t length = buf_cnt;
2444 /* DANGER!!! beware of unsigned comparision here!!! */
2446 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2447 (image.sections[i].base_address < max_address))
2449 if (image.sections[i].base_address < min_address)
2451 /* clip addresses below */
2452 offset += min_address-image.sections[i].base_address;
2456 if (image.sections[i].base_address + buf_cnt > max_address)
2458 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2461 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2466 image_size += length;
2467 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2468 (unsigned int)length,
2469 image.sections[i].base_address + offset);
2475 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2477 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2478 "in %fs (%0.3f kb/s)", image_size,
2479 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2482 image_close(&image);
2488 COMMAND_HANDLER(handle_dump_image_command)
2490 struct fileio fileio;
2492 uint8_t buffer[560];
2496 struct target *target = get_current_target(CMD_CTX);
2500 command_print(CMD_CTX, "usage: dump_image <filename> <address> <size>");
2505 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2507 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2509 if (fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2514 struct duration bench;
2515 duration_start(&bench);
2517 int retval = ERROR_OK;
2520 size_t size_written;
2521 uint32_t this_run_size = (size > 560) ? 560 : size;
2522 retval = target_read_buffer(target, address, this_run_size, buffer);
2523 if (retval != ERROR_OK)
2528 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2529 if (retval != ERROR_OK)
2534 size -= this_run_size;
2535 address += this_run_size;
2538 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2541 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2543 command_print(CMD_CTX,
2544 "dumped %zu bytes in %fs (%0.3f kb/s)", fileio.size,
2545 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2551 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2555 uint32_t image_size;
2558 uint32_t checksum = 0;
2559 uint32_t mem_checksum = 0;
2563 struct target *target = get_current_target(CMD_CTX);
2567 return ERROR_COMMAND_SYNTAX_ERROR;
2572 LOG_ERROR("no target selected");
2576 struct duration bench;
2577 duration_start(&bench);
2582 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2583 image.base_address = addr;
2584 image.base_address_set = 1;
2588 image.base_address_set = 0;
2589 image.base_address = 0x0;
2592 image.start_address_set = 0;
2594 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2601 for (i = 0; i < image.num_sections; i++)
2603 buffer = malloc(image.sections[i].size);
2606 command_print(CMD_CTX,
2607 "error allocating buffer for section (%d bytes)",
2608 (int)(image.sections[i].size));
2611 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2619 /* calculate checksum of image */
2620 image_calculate_checksum(buffer, buf_cnt, &checksum);
2622 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2623 if (retval != ERROR_OK)
2629 if (checksum != mem_checksum)
2631 /* failed crc checksum, fall back to a binary compare */
2634 command_print(CMD_CTX, "checksum mismatch - attempting binary compare");
2636 data = (uint8_t*)malloc(buf_cnt);
2638 /* Can we use 32bit word accesses? */
2640 int count = buf_cnt;
2641 if ((count % 4) == 0)
2646 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2647 if (retval == ERROR_OK)
2650 for (t = 0; t < buf_cnt; t++)
2652 if (data[t] != buffer[t])
2654 command_print(CMD_CTX,
2655 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2656 (unsigned)(t + image.sections[i].base_address),
2661 retval = ERROR_FAIL;
2675 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2676 image.sections[i].base_address,
2681 image_size += buf_cnt;
2684 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2686 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2687 "in %fs (%0.3f kb/s)", image_size,
2688 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2691 image_close(&image);
2696 COMMAND_HANDLER(handle_verify_image_command)
2698 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2701 COMMAND_HANDLER(handle_test_image_command)
2703 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2706 static int handle_bp_command_list(struct command_context *cmd_ctx)
2708 struct target *target = get_current_target(cmd_ctx);
2709 struct breakpoint *breakpoint = target->breakpoints;
2712 if (breakpoint->type == BKPT_SOFT)
2714 char* buf = buf_to_str(breakpoint->orig_instr,
2715 breakpoint->length, 16);
2716 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2717 breakpoint->address,
2719 breakpoint->set, buf);
2724 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2725 breakpoint->address,
2726 breakpoint->length, breakpoint->set);
2729 breakpoint = breakpoint->next;
2734 static int handle_bp_command_set(struct command_context *cmd_ctx,
2735 uint32_t addr, uint32_t length, int hw)
2737 struct target *target = get_current_target(cmd_ctx);
2738 int retval = breakpoint_add(target, addr, length, hw);
2739 if (ERROR_OK == retval)
2740 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2742 LOG_ERROR("Failure setting breakpoint");
2746 COMMAND_HANDLER(handle_bp_command)
2749 return handle_bp_command_list(CMD_CTX);
2751 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2753 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2754 return ERROR_COMMAND_SYNTAX_ERROR;
2758 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2760 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2765 if (strcmp(CMD_ARGV[2], "hw") == 0)
2768 return ERROR_COMMAND_SYNTAX_ERROR;
2771 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2774 COMMAND_HANDLER(handle_rbp_command)
2777 return ERROR_COMMAND_SYNTAX_ERROR;
2780 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2782 struct target *target = get_current_target(CMD_CTX);
2783 breakpoint_remove(target, addr);
2788 COMMAND_HANDLER(handle_wp_command)
2790 struct target *target = get_current_target(CMD_CTX);
2794 struct watchpoint *watchpoint = target->watchpoints;
2798 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2799 ", len: 0x%8.8" PRIx32
2800 ", r/w/a: %i, value: 0x%8.8" PRIx32
2801 ", mask: 0x%8.8" PRIx32,
2802 watchpoint->address,
2804 (int)watchpoint->rw,
2807 watchpoint = watchpoint->next;
2812 enum watchpoint_rw type = WPT_ACCESS;
2814 uint32_t length = 0;
2815 uint32_t data_value = 0x0;
2816 uint32_t data_mask = 0xffffffff;
2821 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2824 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2827 switch (CMD_ARGV[2][0])
2839 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2840 return ERROR_COMMAND_SYNTAX_ERROR;
2844 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2845 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2849 command_print(CMD_CTX, "usage: wp [address length "
2850 "[(r|w|a) [value [mask]]]]");
2851 return ERROR_COMMAND_SYNTAX_ERROR;
2854 int retval = watchpoint_add(target, addr, length, type,
2855 data_value, data_mask);
2856 if (ERROR_OK != retval)
2857 LOG_ERROR("Failure setting watchpoints");
2862 COMMAND_HANDLER(handle_rwp_command)
2865 return ERROR_COMMAND_SYNTAX_ERROR;
2868 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2870 struct target *target = get_current_target(CMD_CTX);
2871 watchpoint_remove(target, addr);
2878 * Translate a virtual address to a physical address.
2880 * The low-level target implementation must have logged a detailed error
2881 * which is forwarded to telnet/GDB session.
2883 COMMAND_HANDLER(handle_virt2phys_command)
2886 return ERROR_COMMAND_SYNTAX_ERROR;
2889 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
2892 struct target *target = get_current_target(CMD_CTX);
2893 int retval = target->type->virt2phys(target, va, &pa);
2894 if (retval == ERROR_OK)
2895 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
2900 static void writeData(FILE *f, const void *data, size_t len)
2902 size_t written = fwrite(data, 1, len, f);
2904 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2907 static void writeLong(FILE *f, int l)
2910 for (i = 0; i < 4; i++)
2912 char c = (l >> (i*8))&0xff;
2913 writeData(f, &c, 1);
2918 static void writeString(FILE *f, char *s)
2920 writeData(f, s, strlen(s));
2923 /* Dump a gmon.out histogram file. */
2924 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
2927 FILE *f = fopen(filename, "w");
2930 writeString(f, "gmon");
2931 writeLong(f, 0x00000001); /* Version */
2932 writeLong(f, 0); /* padding */
2933 writeLong(f, 0); /* padding */
2934 writeLong(f, 0); /* padding */
2936 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2937 writeData(f, &zero, 1);
2939 /* figure out bucket size */
2940 uint32_t min = samples[0];
2941 uint32_t max = samples[0];
2942 for (i = 0; i < sampleNum; i++)
2944 if (min > samples[i])
2948 if (max < samples[i])
2954 int addressSpace = (max-min + 1);
2956 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2957 uint32_t length = addressSpace;
2958 if (length > maxBuckets)
2960 length = maxBuckets;
2962 int *buckets = malloc(sizeof(int)*length);
2963 if (buckets == NULL)
2968 memset(buckets, 0, sizeof(int)*length);
2969 for (i = 0; i < sampleNum;i++)
2971 uint32_t address = samples[i];
2972 long long a = address-min;
2973 long long b = length-1;
2974 long long c = addressSpace-1;
2975 int index = (a*b)/c; /* danger!!!! int32 overflows */
2979 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2980 writeLong(f, min); /* low_pc */
2981 writeLong(f, max); /* high_pc */
2982 writeLong(f, length); /* # of samples */
2983 writeLong(f, 64000000); /* 64MHz */
2984 writeString(f, "seconds");
2985 for (i = 0; i < (15-strlen("seconds")); i++)
2986 writeData(f, &zero, 1);
2987 writeString(f, "s");
2989 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2991 char *data = malloc(2*length);
2994 for (i = 0; i < length;i++)
3003 data[i*2 + 1]=(val >> 8)&0xff;
3006 writeData(f, data, length * 2);
3016 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
3017 COMMAND_HANDLER(handle_profile_command)
3019 struct target *target = get_current_target(CMD_CTX);
3020 struct timeval timeout, now;
3022 gettimeofday(&timeout, NULL);
3025 return ERROR_COMMAND_SYNTAX_ERROR;
3028 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3030 timeval_add_time(&timeout, offset, 0);
3032 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3034 static const int maxSample = 10000;
3035 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3036 if (samples == NULL)
3040 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3041 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3046 target_poll(target);
3047 if (target->state == TARGET_HALTED)
3049 uint32_t t=*((uint32_t *)reg->value);
3050 samples[numSamples++]=t;
3051 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3052 target_poll(target);
3053 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3054 } else if (target->state == TARGET_RUNNING)
3056 /* We want to quickly sample the PC. */
3057 if ((retval = target_halt(target)) != ERROR_OK)
3064 command_print(CMD_CTX, "Target not halted or running");
3068 if (retval != ERROR_OK)
3073 gettimeofday(&now, NULL);
3074 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3076 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3077 if ((retval = target_poll(target)) != ERROR_OK)
3082 if (target->state == TARGET_HALTED)
3084 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3086 if ((retval = target_poll(target)) != ERROR_OK)
3091 writeGmon(samples, numSamples, CMD_ARGV[1]);
3092 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3101 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3104 Jim_Obj *nameObjPtr, *valObjPtr;
3107 namebuf = alloc_printf("%s(%d)", varname, idx);
3111 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3112 valObjPtr = Jim_NewIntObj(interp, val);
3113 if (!nameObjPtr || !valObjPtr)
3119 Jim_IncrRefCount(nameObjPtr);
3120 Jim_IncrRefCount(valObjPtr);
3121 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3122 Jim_DecrRefCount(interp, nameObjPtr);
3123 Jim_DecrRefCount(interp, valObjPtr);
3125 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3129 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3131 struct command_context *context;
3132 struct target *target;
3134 context = Jim_GetAssocData(interp, "context");
3135 if (context == NULL)
3137 LOG_ERROR("mem2array: no command context");
3140 target = get_current_target(context);
3143 LOG_ERROR("mem2array: no current target");
3147 return target_mem2array(interp, target, argc-1, argv + 1);
3150 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3158 const char *varname;
3162 /* argv[1] = name of array to receive the data
3163 * argv[2] = desired width
3164 * argv[3] = memory address
3165 * argv[4] = count of times to read
3168 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3171 varname = Jim_GetString(argv[0], &len);
3172 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3174 e = Jim_GetLong(interp, argv[1], &l);
3180 e = Jim_GetLong(interp, argv[2], &l);
3185 e = Jim_GetLong(interp, argv[3], &l);
3201 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3202 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3206 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3207 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3210 if ((addr + (len * width)) < addr) {
3211 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3212 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3215 /* absurd transfer size? */
3217 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3218 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3223 ((width == 2) && ((addr & 1) == 0)) ||
3224 ((width == 4) && ((addr & 3) == 0))) {
3228 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3229 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3232 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3241 size_t buffersize = 4096;
3242 uint8_t *buffer = malloc(buffersize);
3249 /* Slurp... in buffer size chunks */
3251 count = len; /* in objects.. */
3252 if (count > (buffersize/width)) {
3253 count = (buffersize/width);
3256 retval = target_read_memory(target, addr, width, count, buffer);
3257 if (retval != ERROR_OK) {
3259 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3263 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3264 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3268 v = 0; /* shut up gcc */
3269 for (i = 0 ;i < count ;i++, n++) {
3272 v = target_buffer_get_u32(target, &buffer[i*width]);
3275 v = target_buffer_get_u16(target, &buffer[i*width]);
3278 v = buffer[i] & 0x0ff;
3281 new_int_array_element(interp, varname, n, v);
3289 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3294 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3297 Jim_Obj *nameObjPtr, *valObjPtr;
3301 namebuf = alloc_printf("%s(%d)", varname, idx);
3305 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3312 Jim_IncrRefCount(nameObjPtr);
3313 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3314 Jim_DecrRefCount(interp, nameObjPtr);
3316 if (valObjPtr == NULL)
3319 result = Jim_GetLong(interp, valObjPtr, &l);
3320 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3325 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3327 struct command_context *context;
3328 struct target *target;
3330 context = Jim_GetAssocData(interp, "context");
3331 if (context == NULL) {
3332 LOG_ERROR("array2mem: no command context");
3335 target = get_current_target(context);
3336 if (target == NULL) {
3337 LOG_ERROR("array2mem: no current target");
3341 return target_array2mem(interp,target, argc-1, argv + 1);
3343 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3351 const char *varname;
3355 /* argv[1] = name of array to get the data
3356 * argv[2] = desired width
3357 * argv[3] = memory address
3358 * argv[4] = count to write
3361 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3364 varname = Jim_GetString(argv[0], &len);
3365 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3367 e = Jim_GetLong(interp, argv[1], &l);
3373 e = Jim_GetLong(interp, argv[2], &l);
3378 e = Jim_GetLong(interp, argv[3], &l);
3394 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3395 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3399 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3400 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3403 if ((addr + (len * width)) < addr) {
3404 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3405 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3408 /* absurd transfer size? */
3410 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3411 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3416 ((width == 2) && ((addr & 1) == 0)) ||
3417 ((width == 4) && ((addr & 3) == 0))) {
3421 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3422 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3425 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3436 size_t buffersize = 4096;
3437 uint8_t *buffer = malloc(buffersize);
3442 /* Slurp... in buffer size chunks */
3444 count = len; /* in objects.. */
3445 if (count > (buffersize/width)) {
3446 count = (buffersize/width);
3449 v = 0; /* shut up gcc */
3450 for (i = 0 ;i < count ;i++, n++) {
3451 get_int_array_element(interp, varname, n, &v);
3454 target_buffer_set_u32(target, &buffer[i*width], v);
3457 target_buffer_set_u16(target, &buffer[i*width], v);
3460 buffer[i] = v & 0x0ff;
3466 retval = target_write_memory(target, addr, width, count, buffer);
3467 if (retval != ERROR_OK) {
3469 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3473 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3474 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3482 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3487 void target_all_handle_event(enum target_event e)
3489 struct target *target;
3491 LOG_DEBUG("**all*targets: event: %d, %s",
3493 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3495 target = all_targets;
3497 target_handle_event(target, e);
3498 target = target->next;
3503 /* FIX? should we propagate errors here rather than printing them
3506 void target_handle_event(struct target *target, enum target_event e)
3508 struct target_event_action *teap;
3510 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3511 if (teap->event == e) {
3512 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3513 target->target_number,
3514 target_name(target),
3515 target_type_name(target),
3517 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3518 Jim_GetString(teap->body, NULL));
3519 if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3521 Jim_PrintErrorMessage(interp);
3528 * Returns true only if the target has a handler for the specified event.
3530 bool target_has_event_action(struct target *target, enum target_event event)
3532 struct target_event_action *teap;
3534 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3535 if (teap->event == event)
3541 enum target_cfg_param {
3544 TCFG_WORK_AREA_VIRT,
3545 TCFG_WORK_AREA_PHYS,
3546 TCFG_WORK_AREA_SIZE,
3547 TCFG_WORK_AREA_BACKUP,
3550 TCFG_CHAIN_POSITION,
3553 static Jim_Nvp nvp_config_opts[] = {
3554 { .name = "-type", .value = TCFG_TYPE },
3555 { .name = "-event", .value = TCFG_EVENT },
3556 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3557 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3558 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3559 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3560 { .name = "-endian" , .value = TCFG_ENDIAN },
3561 { .name = "-variant", .value = TCFG_VARIANT },
3562 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3564 { .name = NULL, .value = -1 }
3567 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3575 /* parse config or cget options ... */
3576 while (goi->argc > 0) {
3577 Jim_SetEmptyResult(goi->interp);
3578 /* Jim_GetOpt_Debug(goi); */
3580 if (target->type->target_jim_configure) {
3581 /* target defines a configure function */
3582 /* target gets first dibs on parameters */
3583 e = (*(target->type->target_jim_configure))(target, goi);
3592 /* otherwise we 'continue' below */
3594 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3596 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3602 if (goi->isconfigure) {
3603 Jim_SetResult_sprintf(goi->interp,
3604 "not settable: %s", n->name);
3608 if (goi->argc != 0) {
3609 Jim_WrongNumArgs(goi->interp,
3610 goi->argc, goi->argv,
3615 Jim_SetResultString(goi->interp,
3616 target_type_name(target), -1);
3620 if (goi->argc == 0) {
3621 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3625 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3627 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3631 if (goi->isconfigure) {
3632 if (goi->argc != 1) {
3633 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3637 if (goi->argc != 0) {
3638 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3644 struct target_event_action *teap;
3646 teap = target->event_action;
3647 /* replace existing? */
3649 if (teap->event == (enum target_event)n->value) {
3655 if (goi->isconfigure) {
3656 bool replace = true;
3659 teap = calloc(1, sizeof(*teap));
3662 teap->event = n->value;
3663 Jim_GetOpt_Obj(goi, &o);
3665 Jim_DecrRefCount(interp, teap->body);
3667 teap->body = Jim_DuplicateObj(goi->interp, o);
3670 * Tcl/TK - "tk events" have a nice feature.
3671 * See the "BIND" command.
3672 * We should support that here.
3673 * You can specify %X and %Y in the event code.
3674 * The idea is: %T - target name.
3675 * The idea is: %N - target number
3676 * The idea is: %E - event name.
3678 Jim_IncrRefCount(teap->body);
3682 /* add to head of event list */
3683 teap->next = target->event_action;
3684 target->event_action = teap;
3686 Jim_SetEmptyResult(goi->interp);
3690 Jim_SetEmptyResult(goi->interp);
3692 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3699 case TCFG_WORK_AREA_VIRT:
3700 if (goi->isconfigure) {
3701 target_free_all_working_areas(target);
3702 e = Jim_GetOpt_Wide(goi, &w);
3706 target->working_area_virt = w;
3707 target->working_area_virt_spec = true;
3709 if (goi->argc != 0) {
3713 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3717 case TCFG_WORK_AREA_PHYS:
3718 if (goi->isconfigure) {
3719 target_free_all_working_areas(target);
3720 e = Jim_GetOpt_Wide(goi, &w);
3724 target->working_area_phys = w;
3725 target->working_area_phys_spec = true;
3727 if (goi->argc != 0) {
3731 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3735 case TCFG_WORK_AREA_SIZE:
3736 if (goi->isconfigure) {
3737 target_free_all_working_areas(target);
3738 e = Jim_GetOpt_Wide(goi, &w);
3742 target->working_area_size = w;
3744 if (goi->argc != 0) {
3748 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3752 case TCFG_WORK_AREA_BACKUP:
3753 if (goi->isconfigure) {
3754 target_free_all_working_areas(target);
3755 e = Jim_GetOpt_Wide(goi, &w);
3759 /* make this exactly 1 or 0 */
3760 target->backup_working_area = (!!w);
3762 if (goi->argc != 0) {
3766 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3767 /* loop for more e*/
3771 if (goi->isconfigure) {
3772 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3774 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3777 target->endianness = n->value;
3779 if (goi->argc != 0) {
3783 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3784 if (n->name == NULL) {
3785 target->endianness = TARGET_LITTLE_ENDIAN;
3786 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3788 Jim_SetResultString(goi->interp, n->name, -1);
3793 if (goi->isconfigure) {
3794 if (goi->argc < 1) {
3795 Jim_SetResult_sprintf(goi->interp,
3800 if (target->variant) {
3801 free((void *)(target->variant));
3803 e = Jim_GetOpt_String(goi, &cp, NULL);
3804 target->variant = strdup(cp);
3806 if (goi->argc != 0) {
3810 Jim_SetResultString(goi->interp, target->variant,-1);
3813 case TCFG_CHAIN_POSITION:
3814 if (goi->isconfigure) {
3816 struct jtag_tap *tap;
3817 target_free_all_working_areas(target);
3818 e = Jim_GetOpt_Obj(goi, &o);
3822 tap = jtag_tap_by_jim_obj(goi->interp, o);
3826 /* make this exactly 1 or 0 */
3829 if (goi->argc != 0) {
3833 Jim_SetResultString(interp, target->tap->dotted_name, -1);
3834 /* loop for more e*/
3837 } /* while (goi->argc) */
3840 /* done - we return */
3844 /** this is the 'tcl' handler for the target specific command */
3845 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3850 uint8_t target_buf[32];
3852 struct target *target;
3853 struct command_context *cmd_ctx;
3860 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3861 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3862 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3863 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3871 TS_CMD_INVOKE_EVENT,
3874 static const Jim_Nvp target_options[] = {
3875 { .name = "configure", .value = TS_CMD_CONFIGURE },
3876 { .name = "cget", .value = TS_CMD_CGET },
3877 { .name = "mww", .value = TS_CMD_MWW },
3878 { .name = "mwh", .value = TS_CMD_MWH },
3879 { .name = "mwb", .value = TS_CMD_MWB },
3880 { .name = "mdw", .value = TS_CMD_MDW },
3881 { .name = "mdh", .value = TS_CMD_MDH },
3882 { .name = "mdb", .value = TS_CMD_MDB },
3883 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3884 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3885 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3886 { .name = "curstate", .value = TS_CMD_CURSTATE },
3888 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3889 { .name = "arp_poll", .value = TS_CMD_POLL },
3890 { .name = "arp_reset", .value = TS_CMD_RESET },
3891 { .name = "arp_halt", .value = TS_CMD_HALT },
3892 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3893 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3895 { .name = NULL, .value = -1 },
3898 /* go past the "command" */
3899 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3901 target = Jim_CmdPrivData(goi.interp);
3902 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3904 /* commands here are in an NVP table */
3905 e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3907 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3910 /* Assume blank result */
3911 Jim_SetEmptyResult(goi.interp);
3914 case TS_CMD_CONFIGURE:
3916 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3919 goi.isconfigure = 1;
3920 return target_configure(&goi, target);
3922 // some things take params
3924 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3927 goi.isconfigure = 0;
3928 return target_configure(&goi, target);
3936 * argv[3] = optional count.
3939 if ((goi.argc == 2) || (goi.argc == 3)) {
3943 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3947 e = Jim_GetOpt_Wide(&goi, &a);
3952 e = Jim_GetOpt_Wide(&goi, &b);
3956 if (goi.argc == 3) {
3957 e = Jim_GetOpt_Wide(&goi, &c);
3967 target_buffer_set_u32(target, target_buf, b);
3971 target_buffer_set_u16(target, target_buf, b);
3975 target_buffer_set_u8(target, target_buf, b);
3979 for (x = 0 ; x < c ; x++) {
3980 e = target_write_memory(target, a, b, 1, target_buf);
3981 if (e != ERROR_OK) {
3982 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3995 /* argv[0] = command
3997 * argv[2] = optional count
3999 if ((goi.argc == 2) || (goi.argc == 3)) {
4000 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
4003 e = Jim_GetOpt_Wide(&goi, &a);
4008 e = Jim_GetOpt_Wide(&goi, &c);
4015 b = 1; /* shut up gcc */
4028 /* convert to "bytes" */
4030 /* count is now in 'BYTES' */
4036 e = target_read_memory(target, a, b, y / b, target_buf);
4037 if (e != ERROR_OK) {
4038 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4042 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4045 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
4046 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
4047 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4049 for (; (x < 16) ; x += 4) {
4050 Jim_fprintf(interp, interp->cookie_stdout, " ");
4054 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
4055 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
4056 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4058 for (; (x < 16) ; x += 2) {
4059 Jim_fprintf(interp, interp->cookie_stdout, " ");
4064 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4065 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4066 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4068 for (; (x < 16) ; x += 1) {
4069 Jim_fprintf(interp, interp->cookie_stdout, " ");
4073 /* ascii-ify the bytes */
4074 for (x = 0 ; x < y ; x++) {
4075 if ((target_buf[x] >= 0x20) &&
4076 (target_buf[x] <= 0x7e)) {
4080 target_buf[x] = '.';
4085 target_buf[x] = ' ';
4090 /* print - with a newline */
4091 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4097 case TS_CMD_MEM2ARRAY:
4098 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4100 case TS_CMD_ARRAY2MEM:
4101 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4103 case TS_CMD_EXAMINE:
4105 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4108 if (!target->tap->enabled)
4109 goto err_tap_disabled;
4110 e = target->type->examine(target);
4111 if (e != ERROR_OK) {
4112 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4118 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4121 if (!target->tap->enabled)
4122 goto err_tap_disabled;
4123 if (!(target_was_examined(target))) {
4124 e = ERROR_TARGET_NOT_EXAMINED;
4126 e = target->type->poll(target);
4128 if (e != ERROR_OK) {
4129 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4136 if (goi.argc != 2) {
4137 Jim_WrongNumArgs(interp, 2, argv,
4138 "([tT]|[fF]|assert|deassert) BOOL");
4141 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4143 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4146 /* the halt or not param */
4147 e = Jim_GetOpt_Wide(&goi, &a);
4151 if (!target->tap->enabled)
4152 goto err_tap_disabled;
4153 if (!target->type->assert_reset
4154 || !target->type->deassert_reset) {
4155 Jim_SetResult_sprintf(interp,
4156 "No target-specific reset for %s",
4157 target_name(target));
4160 /* determine if we should halt or not. */
4161 target->reset_halt = !!a;
4162 /* When this happens - all workareas are invalid. */
4163 target_free_all_working_areas_restore(target, 0);
4166 if (n->value == NVP_ASSERT) {
4167 e = target->type->assert_reset(target);
4169 e = target->type->deassert_reset(target);
4171 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4174 Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4177 if (!target->tap->enabled)
4178 goto err_tap_disabled;
4179 e = target->type->halt(target);
4180 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4181 case TS_CMD_WAITSTATE:
4182 /* params: <name> statename timeoutmsecs */
4183 if (goi.argc != 2) {
4184 Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4187 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4189 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4192 e = Jim_GetOpt_Wide(&goi, &a);
4196 if (!target->tap->enabled)
4197 goto err_tap_disabled;
4198 e = target_wait_state(target, n->value, a);
4199 if (e != ERROR_OK) {
4200 Jim_SetResult_sprintf(goi.interp,
4201 "target: %s wait %s fails (%d) %s",
4202 target_name(target), n->name,
4203 e, target_strerror_safe(e));
4208 case TS_CMD_EVENTLIST:
4209 /* List for human, Events defined for this target.
4210 * scripts/programs should use 'name cget -event NAME'
4213 struct target_event_action *teap;
4214 teap = target->event_action;
4215 command_print(cmd_ctx,
4216 "Event actions for target (%d) %s\n",
4217 target->target_number,
4218 target_name(target));
4219 command_print(cmd_ctx, "%-25s | Body", "Event");
4220 command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4222 command_print(cmd_ctx,
4224 Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4225 Jim_GetString(teap->body, NULL));
4228 command_print(cmd_ctx, "***END***");
4231 case TS_CMD_CURSTATE:
4232 if (goi.argc != 0) {
4233 Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4236 Jim_SetResultString(goi.interp,
4237 target_state_name( target ),
4240 case TS_CMD_INVOKE_EVENT:
4241 if (goi.argc != 1) {
4242 Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4245 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4247 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4250 target_handle_event(target, n->value);
4256 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4260 static int target_create(Jim_GetOptInfo *goi)
4268 struct target *target;
4269 struct command_context *cmd_ctx;
4271 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4272 if (goi->argc < 3) {
4273 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4278 Jim_GetOpt_Obj(goi, &new_cmd);
4279 /* does this command exist? */
4280 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4282 cp = Jim_GetString(new_cmd, NULL);
4283 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4288 e = Jim_GetOpt_String(goi, &cp2, NULL);
4290 /* now does target type exist */
4291 for (x = 0 ; target_types[x] ; x++) {
4292 if (0 == strcmp(cp, target_types[x]->name)) {
4297 if (target_types[x] == NULL) {
4298 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4299 for (x = 0 ; target_types[x] ; x++) {
4300 if (target_types[x + 1]) {
4301 Jim_AppendStrings(goi->interp,
4302 Jim_GetResult(goi->interp),
4303 target_types[x]->name,
4306 Jim_AppendStrings(goi->interp,
4307 Jim_GetResult(goi->interp),
4309 target_types[x]->name,NULL);
4316 target = calloc(1,sizeof(struct target));
4317 /* set target number */
4318 target->target_number = new_target_number();
4320 /* allocate memory for each unique target type */
4321 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4323 memcpy(target->type, target_types[x], sizeof(struct target_type));
4325 /* will be set by "-endian" */
4326 target->endianness = TARGET_ENDIAN_UNKNOWN;
4328 target->working_area = 0x0;
4329 target->working_area_size = 0x0;
4330 target->working_areas = NULL;
4331 target->backup_working_area = 0;
4333 target->state = TARGET_UNKNOWN;
4334 target->debug_reason = DBG_REASON_UNDEFINED;
4335 target->reg_cache = NULL;
4336 target->breakpoints = NULL;
4337 target->watchpoints = NULL;
4338 target->next = NULL;
4339 target->arch_info = NULL;
4341 target->display = 1;
4343 target->halt_issued = false;
4345 /* initialize trace information */
4346 target->trace_info = malloc(sizeof(struct trace));
4347 target->trace_info->num_trace_points = 0;
4348 target->trace_info->trace_points_size = 0;
4349 target->trace_info->trace_points = NULL;
4350 target->trace_info->trace_history_size = 0;
4351 target->trace_info->trace_history = NULL;
4352 target->trace_info->trace_history_pos = 0;
4353 target->trace_info->trace_history_overflowed = 0;
4355 target->dbgmsg = NULL;
4356 target->dbg_msg_enabled = 0;
4358 target->endianness = TARGET_ENDIAN_UNKNOWN;
4360 /* Do the rest as "configure" options */
4361 goi->isconfigure = 1;
4362 e = target_configure(goi, target);
4364 if (target->tap == NULL)
4366 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4376 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4377 /* default endian to little if not specified */
4378 target->endianness = TARGET_LITTLE_ENDIAN;
4381 /* incase variant is not set */
4382 if (!target->variant)
4383 target->variant = strdup("");
4385 cp = Jim_GetString(new_cmd, NULL);
4386 target->cmd_name = strdup(cp);
4388 /* create the target specific commands */
4389 if (target->type->commands) {
4390 e = register_commands(cmd_ctx, NULL, target->type->commands);
4392 LOG_ERROR("unable to register '%s' commands", cp);
4394 if (target->type->target_create) {
4395 (*(target->type->target_create))(target, goi->interp);
4398 /* append to end of list */
4400 struct target **tpp;
4401 tpp = &(all_targets);
4403 tpp = &((*tpp)->next);
4408 /* now - create the new target name command */
4409 const struct command_registration target_command = {
4411 .jim_handler = &tcl_target_func,
4412 .jim_handler_data = target,
4413 .help = "target command group",
4415 struct command *c = register_command(cmd_ctx, NULL, &target_command);
4416 return (NULL != c) ? ERROR_OK : ERROR_FAIL;
4419 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4423 struct command_context *cmd_ctx;
4424 struct target *target;
4427 /* TG = target generic */
4435 const char *target_cmds[] = {
4436 "create", "types", "names", "current", "number",
4438 NULL /* terminate */
4441 LOG_DEBUG("Target command params:");
4442 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4444 cmd_ctx = Jim_GetAssocData(interp, "context");
4446 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4448 if (goi.argc == 0) {
4449 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4453 /* Jim_GetOpt_Debug(&goi); */
4454 r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4461 Jim_Panic(goi.interp,"Why am I here?");
4463 case TG_CMD_CURRENT:
4464 if (goi.argc != 0) {
4465 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4468 Jim_SetResultString(goi.interp,
4469 target_name(get_current_target(cmd_ctx)),
4473 if (goi.argc != 0) {
4474 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4477 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4478 for (x = 0 ; target_types[x] ; x++) {
4479 Jim_ListAppendElement(goi.interp,
4480 Jim_GetResult(goi.interp),
4481 Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4485 if (goi.argc != 0) {
4486 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4489 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4490 target = all_targets;
4492 Jim_ListAppendElement(goi.interp,
4493 Jim_GetResult(goi.interp),
4494 Jim_NewStringObj(goi.interp,
4495 target_name(target), -1));
4496 target = target->next;
4501 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4504 return target_create(&goi);
4507 /* It's OK to remove this mechanism sometime after August 2010 or so */
4508 LOG_WARNING("don't use numbers as target identifiers; use names");
4509 if (goi.argc != 1) {
4510 Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4513 e = Jim_GetOpt_Wide(&goi, &w);
4517 for (x = 0, target = all_targets; target; target = target->next, x++) {
4518 if (target->target_number == w)
4521 if (target == NULL) {
4522 Jim_SetResult_sprintf(goi.interp,
4523 "Target: number %d does not exist", (int)(w));
4526 Jim_SetResultString(goi.interp, target_name(target), -1);
4529 if (goi.argc != 0) {
4530 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4533 for (x = 0, target = all_targets; target; target = target->next, x++)
4535 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4551 static int fastload_num;
4552 static struct FastLoad *fastload;
4554 static void free_fastload(void)
4556 if (fastload != NULL)
4559 for (i = 0; i < fastload_num; i++)
4561 if (fastload[i].data)
4562 free(fastload[i].data);
4572 COMMAND_HANDLER(handle_fast_load_image_command)
4576 uint32_t image_size;
4577 uint32_t min_address = 0;
4578 uint32_t max_address = 0xffffffff;
4583 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4584 &image, &min_address, &max_address);
4585 if (ERROR_OK != retval)
4588 struct duration bench;
4589 duration_start(&bench);
4591 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
4598 fastload_num = image.num_sections;
4599 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4600 if (fastload == NULL)
4602 image_close(&image);
4605 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4606 for (i = 0; i < image.num_sections; i++)
4608 buffer = malloc(image.sections[i].size);
4611 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
4612 (int)(image.sections[i].size));
4616 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4622 uint32_t offset = 0;
4623 uint32_t length = buf_cnt;
4626 /* DANGER!!! beware of unsigned comparision here!!! */
4628 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4629 (image.sections[i].base_address < max_address))
4631 if (image.sections[i].base_address < min_address)
4633 /* clip addresses below */
4634 offset += min_address-image.sections[i].base_address;
4638 if (image.sections[i].base_address + buf_cnt > max_address)
4640 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4643 fastload[i].address = image.sections[i].base_address + offset;
4644 fastload[i].data = malloc(length);
4645 if (fastload[i].data == NULL)
4650 memcpy(fastload[i].data, buffer + offset, length);
4651 fastload[i].length = length;
4653 image_size += length;
4654 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
4655 (unsigned int)length,
4656 ((unsigned int)(image.sections[i].base_address + offset)));
4662 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4664 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
4665 "in %fs (%0.3f kb/s)", image_size,
4666 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4668 command_print(CMD_CTX,
4669 "WARNING: image has not been loaded to target!"
4670 "You can issue a 'fast_load' to finish loading.");
4673 image_close(&image);
4675 if (retval != ERROR_OK)
4683 COMMAND_HANDLER(handle_fast_load_command)
4686 return ERROR_COMMAND_SYNTAX_ERROR;
4687 if (fastload == NULL)
4689 LOG_ERROR("No image in memory");
4693 int ms = timeval_ms();
4695 int retval = ERROR_OK;
4696 for (i = 0; i < fastload_num;i++)
4698 struct target *target = get_current_target(CMD_CTX);
4699 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
4700 (unsigned int)(fastload[i].address),
4701 (unsigned int)(fastload[i].length));
4702 if (retval == ERROR_OK)
4704 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4706 size += fastload[i].length;
4708 int after = timeval_ms();
4709 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4713 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4715 struct command_context *context;
4716 struct target *target;
4719 context = Jim_GetAssocData(interp, "context");
4720 if (context == NULL) {
4721 LOG_ERROR("array2mem: no command context");
4724 target = get_current_target(context);
4725 if (target == NULL) {
4726 LOG_ERROR("array2mem: no current target");
4730 if ((argc < 6) || (argc > 7))
4744 e = Jim_GetLong(interp, argv[1], &l);
4750 e = Jim_GetLong(interp, argv[2], &l);
4756 e = Jim_GetLong(interp, argv[3], &l);
4762 e = Jim_GetLong(interp, argv[4], &l);
4768 e = Jim_GetLong(interp, argv[5], &l);
4778 e = Jim_GetLong(interp, argv[6], &l);
4784 retval = target_mcr(target, cpnum, op1, op2, CRn, CRm, value);
4785 if (retval != ERROR_OK)
4789 retval = target_mrc(target, cpnum, op1, op2, CRn, CRm, &value);
4790 if (retval != ERROR_OK)
4793 Jim_SetResult(interp, Jim_NewIntObj(interp, value));
4799 static const struct command_registration target_command_handlers[] = {
4802 .handler = &handle_targets_command,
4803 .mode = COMMAND_ANY,
4804 .help = "change current command line target (one parameter) "
4805 "or list targets (no parameters)",
4806 .usage = "[<new_current_target>]",
4810 .mode = COMMAND_CONFIG,
4811 .jim_handler = &jim_target,
4812 .help = "configure target",
4814 COMMAND_REGISTRATION_DONE
4817 int target_register_commands(struct command_context *cmd_ctx)
4819 return register_commands(cmd_ctx, NULL, target_command_handlers);
4822 static const struct command_registration target_exec_command_handlers[] = {
4824 .name = "fast_load_image",
4825 .handler = &handle_fast_load_image_command,
4826 .mode = COMMAND_ANY,
4827 .help = "Load image into memory, mainly for profiling purposes",
4828 .usage = "<file> <address> ['bin'|'ihex'|'elf'|'s19'] "
4829 "[min_address] [max_length]",
4832 .name = "fast_load",
4833 .handler = &handle_fast_load_command,
4834 .mode = COMMAND_ANY,
4835 .help = "loads active fast load image to current target "
4836 "- mainly for profiling purposes",
4840 .handler = &handle_profile_command,
4841 .mode = COMMAND_EXEC,
4842 .help = "profiling samples the CPU PC",
4844 /** @todo don't register virt2phys() unless target supports it */
4846 .name = "virt2phys",
4847 .handler = &handle_virt2phys_command,
4848 .mode = COMMAND_ANY,
4849 .help = "translate a virtual address into a physical address",
4854 .handler = &handle_reg_command,
4855 .mode = COMMAND_EXEC,
4856 .help = "display or set a register",
4861 .handler = &handle_poll_command,
4862 .mode = COMMAND_EXEC,
4863 .help = "poll target state",
4866 .name = "wait_halt",
4867 .handler = &handle_wait_halt_command,
4868 .mode = COMMAND_EXEC,
4869 .help = "wait for target halt",
4870 .usage = "[time (s)]",
4874 .handler = &handle_halt_command,
4875 .mode = COMMAND_EXEC,
4876 .help = "halt target",
4880 .handler = &handle_resume_command,
4881 .mode = COMMAND_EXEC,
4882 .help = "resume target",
4883 .usage = "[<address>]",
4887 .handler = &handle_reset_command,
4888 .mode = COMMAND_EXEC,
4889 .usage = "[run|halt|init]",
4890 .help = "Reset all targets into the specified mode."
4891 "Default reset mode is run, if not given.",
4894 .name = "soft_reset_halt",
4895 .handler = &handle_soft_reset_halt_command,
4896 .mode = COMMAND_EXEC,
4897 .help = "halt the target and do a soft reset",
4902 .handler = &handle_step_command,
4903 .mode = COMMAND_EXEC,
4904 .help = "step one instruction from current PC or [addr]",
4905 .usage = "[<address>]",
4910 .handler = &handle_md_command,
4911 .mode = COMMAND_EXEC,
4912 .help = "display memory words",
4913 .usage = "[phys] <addr> [count]",
4917 .handler = &handle_md_command,
4918 .mode = COMMAND_EXEC,
4919 .help = "display memory half-words",
4920 .usage = "[phys] <addr> [count]",
4924 .handler = &handle_md_command,
4925 .mode = COMMAND_EXEC,
4926 .help = "display memory bytes",
4927 .usage = "[phys] <addr> [count]",
4932 .handler = &handle_mw_command,
4933 .mode = COMMAND_EXEC,
4934 .help = "write memory word",
4935 .usage = "[phys] <addr> <value> [count]",
4939 .handler = &handle_mw_command,
4940 .mode = COMMAND_EXEC,
4941 .help = "write memory half-word",
4942 .usage = "[phys] <addr> <value> [count]",
4946 .handler = &handle_mw_command,
4947 .mode = COMMAND_EXEC,
4948 .help = "write memory byte",
4949 .usage = "[phys] <addr> <value> [count]",
4954 .handler = &handle_bp_command,
4955 .mode = COMMAND_EXEC,
4956 .help = "list or set breakpoint",
4957 .usage = "[<address> <length> [hw]]",
4961 .handler = &handle_rbp_command,
4962 .mode = COMMAND_EXEC,
4963 .help = "remove breakpoint",
4964 .usage = "<address>",
4969 .handler = &handle_wp_command,
4970 .mode = COMMAND_EXEC,
4971 .help = "list or set watchpoint",
4972 .usage = "[<address> <length> <r/w/a> [value] [mask]]",
4976 .handler = &handle_rwp_command,
4977 .mode = COMMAND_EXEC,
4978 .help = "remove watchpoint",
4979 .usage = "<address>",
4983 .name = "load_image",
4984 .handler = &handle_load_image_command,
4985 .mode = COMMAND_EXEC,
4986 .usage = "<file> <address> ['bin'|'ihex'|'elf'|'s19'] "
4987 "[min_address] [max_length]",
4990 .name = "dump_image",
4991 .handler = &handle_dump_image_command,
4992 .mode = COMMAND_EXEC,
4993 .usage = "<file> <address> <size>",
4996 .name = "verify_image",
4997 .handler = &handle_verify_image_command,
4998 .mode = COMMAND_EXEC,
4999 .usage = "<file> [offset] [type]",
5002 .name = "test_image",
5003 .handler = &handle_test_image_command,
5004 .mode = COMMAND_EXEC,
5005 .usage = "<file> [offset] [type]",
5008 .name = "ocd_mem2array",
5009 .mode = COMMAND_EXEC,
5010 .jim_handler = &jim_mem2array,
5011 .help = "read memory and return as a TCL array "
5012 "for script processing",
5013 .usage = "<arrayname> <width=32|16|8> <address> <count>",
5016 .name = "ocd_array2mem",
5017 .mode = COMMAND_EXEC,
5018 .jim_handler = &jim_array2mem,
5019 .help = "convert a TCL array to memory locations "
5020 "and write the values",
5021 .usage = "<arrayname> <width=32|16|8> <address> <count>",
5023 COMMAND_REGISTRATION_DONE
5025 int target_register_user_commands(struct command_context *cmd_ctx)
5027 int retval = ERROR_OK;
5028 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5031 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5035 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);