1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2009 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
17 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program; if not, write to the *
29 * Free Software Foundation, Inc., *
30 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
31 ***************************************************************************/
37 #include "target_type.h"
38 #include "target_request.h"
39 #include "time_support.h"
46 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
48 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
49 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
50 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
51 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
52 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
53 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
54 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
55 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
56 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
57 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
58 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
59 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
60 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
61 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
62 static int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
63 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
64 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
65 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
66 static int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc);
67 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
68 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
69 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
71 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
72 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
73 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
75 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
76 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
79 extern target_type_t arm7tdmi_target;
80 extern target_type_t arm720t_target;
81 extern target_type_t arm9tdmi_target;
82 extern target_type_t arm920t_target;
83 extern target_type_t arm966e_target;
84 extern target_type_t arm926ejs_target;
85 extern target_type_t fa526_target;
86 extern target_type_t feroceon_target;
87 extern target_type_t dragonite_target;
88 extern target_type_t xscale_target;
89 extern target_type_t cortexm3_target;
90 extern target_type_t cortexa8_target;
91 extern target_type_t arm11_target;
92 extern target_type_t mips_m4k_target;
93 extern target_type_t avr_target;
95 target_type_t *target_types[] =
115 target_t *all_targets = NULL;
116 target_event_callback_t *target_event_callbacks = NULL;
117 target_timer_callback_t *target_timer_callbacks = NULL;
119 const Jim_Nvp nvp_assert[] = {
120 { .name = "assert", NVP_ASSERT },
121 { .name = "deassert", NVP_DEASSERT },
122 { .name = "T", NVP_ASSERT },
123 { .name = "F", NVP_DEASSERT },
124 { .name = "t", NVP_ASSERT },
125 { .name = "f", NVP_DEASSERT },
126 { .name = NULL, .value = -1 }
129 const Jim_Nvp nvp_error_target[] = {
130 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
131 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
132 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
133 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
134 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
135 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
136 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
137 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
138 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
139 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
140 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
141 { .value = -1, .name = NULL }
144 const char *target_strerror_safe(int err)
148 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
149 if (n->name == NULL) {
156 static const Jim_Nvp nvp_target_event[] = {
157 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
158 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
160 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
161 { .value = TARGET_EVENT_HALTED, .name = "halted" },
162 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
163 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
164 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
166 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
167 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
169 /* historical name */
171 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
173 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
174 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
175 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
176 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
177 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
178 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
179 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
180 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
181 { .value = TARGET_EVENT_RESET_INIT , .name = "reset-init" },
182 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
184 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
185 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
187 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
188 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
190 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
191 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
193 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
194 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
196 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
197 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
199 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
200 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
201 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
203 { .name = NULL, .value = -1 }
206 const Jim_Nvp nvp_target_state[] = {
207 { .name = "unknown", .value = TARGET_UNKNOWN },
208 { .name = "running", .value = TARGET_RUNNING },
209 { .name = "halted", .value = TARGET_HALTED },
210 { .name = "reset", .value = TARGET_RESET },
211 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
212 { .name = NULL, .value = -1 },
215 const Jim_Nvp nvp_target_debug_reason [] = {
216 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
217 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
218 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
219 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
220 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
221 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
222 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
223 { .name = NULL, .value = -1 },
226 const Jim_Nvp nvp_target_endian[] = {
227 { .name = "big", .value = TARGET_BIG_ENDIAN },
228 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
229 { .name = "be", .value = TARGET_BIG_ENDIAN },
230 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
231 { .name = NULL, .value = -1 },
234 const Jim_Nvp nvp_reset_modes[] = {
235 { .name = "unknown", .value = RESET_UNKNOWN },
236 { .name = "run" , .value = RESET_RUN },
237 { .name = "halt" , .value = RESET_HALT },
238 { .name = "init" , .value = RESET_INIT },
239 { .name = NULL , .value = -1 },
243 target_state_name( target_t *t )
246 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
248 LOG_ERROR("Invalid target state: %d", (int)(t->state));
249 cp = "(*BUG*unknown*BUG*)";
254 /* determine the number of the new target */
255 static int new_target_number(void)
260 /* number is 0 based */
264 if (x < t->target_number) {
265 x = t->target_number;
272 static int target_continuous_poll = 1;
274 /* read a uint32_t from a buffer in target memory endianness */
275 uint32_t target_buffer_get_u32(target_t *target, const uint8_t *buffer)
277 if (target->endianness == TARGET_LITTLE_ENDIAN)
278 return le_to_h_u32(buffer);
280 return be_to_h_u32(buffer);
283 /* read a uint16_t from a buffer in target memory endianness */
284 uint16_t target_buffer_get_u16(target_t *target, const uint8_t *buffer)
286 if (target->endianness == TARGET_LITTLE_ENDIAN)
287 return le_to_h_u16(buffer);
289 return be_to_h_u16(buffer);
292 /* read a uint8_t from a buffer in target memory endianness */
293 uint8_t target_buffer_get_u8(target_t *target, const uint8_t *buffer)
295 return *buffer & 0x0ff;
298 /* write a uint32_t to a buffer in target memory endianness */
299 void target_buffer_set_u32(target_t *target, uint8_t *buffer, uint32_t value)
301 if (target->endianness == TARGET_LITTLE_ENDIAN)
302 h_u32_to_le(buffer, value);
304 h_u32_to_be(buffer, value);
307 /* write a uint16_t to a buffer in target memory endianness */
308 void target_buffer_set_u16(target_t *target, uint8_t *buffer, uint16_t value)
310 if (target->endianness == TARGET_LITTLE_ENDIAN)
311 h_u16_to_le(buffer, value);
313 h_u16_to_be(buffer, value);
316 /* write a uint8_t to a buffer in target memory endianness */
317 void target_buffer_set_u8(target_t *target, uint8_t *buffer, uint8_t value)
322 /* return a pointer to a configured target; id is name or number */
323 target_t *get_target(const char *id)
327 /* try as tcltarget name */
328 for (target = all_targets; target; target = target->next) {
329 if (target->cmd_name == NULL)
331 if (strcmp(id, target->cmd_name) == 0)
335 /* It's OK to remove this fallback sometime after August 2010 or so */
337 /* no match, try as number */
339 if (parse_uint(id, &num) != ERROR_OK)
342 for (target = all_targets; target; target = target->next) {
343 if (target->target_number == (int)num) {
344 LOG_WARNING("use '%s' as target identifier, not '%u'",
345 target->cmd_name, num);
353 /* returns a pointer to the n-th configured target */
354 static target_t *get_target_by_num(int num)
356 target_t *target = all_targets;
359 if (target->target_number == num) {
362 target = target->next;
368 target_t* get_current_target(command_context_t *cmd_ctx)
370 target_t *target = get_target_by_num(cmd_ctx->current_target);
374 LOG_ERROR("BUG: current_target out of bounds");
381 int target_poll(struct target_s *target)
383 /* We can't poll until after examine */
384 if (!target_was_examined(target))
386 /* Fail silently lest we pollute the log */
389 return target->type->poll(target);
392 int target_halt(struct target_s *target)
394 /* We can't poll until after examine */
395 if (!target_was_examined(target))
397 LOG_ERROR("Target not examined yet");
400 return target->type->halt(target);
403 int target_resume(struct target_s *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
407 /* We can't poll until after examine */
408 if (!target_was_examined(target))
410 LOG_ERROR("Target not examined yet");
414 /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
415 * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
418 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
424 int target_process_reset(struct command_context_s *cmd_ctx, enum target_reset_mode reset_mode)
429 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
430 if (n->name == NULL) {
431 LOG_ERROR("invalid reset mode");
435 /* disable polling during reset to make reset event scripts
436 * more predictable, i.e. dr/irscan & pathmove in events will
437 * not have JTAG operations injected into the middle of a sequence.
439 int save_poll = target_continuous_poll;
440 target_continuous_poll = 0;
442 sprintf(buf, "ocd_process_reset %s", n->name);
443 retval = Jim_Eval(interp, buf);
445 target_continuous_poll = save_poll;
447 if (retval != JIM_OK) {
448 Jim_PrintErrorMessage(interp);
452 /* We want any events to be processed before the prompt */
453 retval = target_call_timer_callbacks_now();
458 static int default_virt2phys(struct target_s *target, uint32_t virtual, uint32_t *physical)
464 static int default_mmu(struct target_s *target, int *enabled)
470 static int default_examine(struct target_s *target)
472 target_set_examined(target);
476 int target_examine_one(struct target_s *target)
478 return target->type->examine(target);
481 static int jtag_enable_callback(enum jtag_event event, void *priv)
483 target_t *target = priv;
485 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
488 jtag_unregister_event_callback(jtag_enable_callback, target);
489 return target_examine_one(target);
493 /* Targets that correctly implement init + examine, i.e.
494 * no communication with target during init:
498 int target_examine(void)
500 int retval = ERROR_OK;
503 for (target = all_targets; target; target = target->next)
505 /* defer examination, but don't skip it */
506 if (!target->tap->enabled) {
507 jtag_register_event_callback(jtag_enable_callback,
511 if ((retval = target_examine_one(target)) != ERROR_OK)
516 const char *target_get_name(struct target_s *target)
518 return target->type->name;
521 static int target_write_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
523 if (!target_was_examined(target))
525 LOG_ERROR("Target not examined yet");
528 return target->type->write_memory_imp(target, address, size, count, buffer);
531 static int target_read_memory_imp(struct target_s *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->read_memory_imp(target, address, size, count, buffer);
541 static int target_soft_reset_halt_imp(struct target_s *target)
543 if (!target_was_examined(target))
545 LOG_ERROR("Target not examined yet");
548 if (!target->type->soft_reset_halt_imp) {
549 LOG_ERROR("Target %s does not support soft_reset_halt",
553 return target->type->soft_reset_halt_imp(target);
556 static int target_run_algorithm_imp(struct target_s *target, int num_mem_params, mem_param_t *mem_params, int num_reg_params, reg_param_t *reg_param, uint32_t entry_point, uint32_t exit_point, int timeout_ms, void *arch_info)
558 if (!target_was_examined(target))
560 LOG_ERROR("Target not examined yet");
563 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);
566 int target_read_memory(struct target_s *target,
567 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
569 return target->type->read_memory(target, address, size, count, buffer);
572 int target_write_memory(struct target_s *target,
573 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
575 return target->type->write_memory(target, address, size, count, buffer);
577 int target_bulk_write_memory(struct target_s *target,
578 uint32_t address, uint32_t count, uint8_t *buffer)
580 return target->type->bulk_write_memory(target, address, count, buffer);
583 int target_add_breakpoint(struct target_s *target,
584 struct breakpoint_s *breakpoint)
586 return target->type->add_breakpoint(target, breakpoint);
588 int target_remove_breakpoint(struct target_s *target,
589 struct breakpoint_s *breakpoint)
591 return target->type->remove_breakpoint(target, breakpoint);
594 int target_add_watchpoint(struct target_s *target,
595 struct watchpoint_s *watchpoint)
597 return target->type->add_watchpoint(target, watchpoint);
599 int target_remove_watchpoint(struct target_s *target,
600 struct watchpoint_s *watchpoint)
602 return target->type->remove_watchpoint(target, watchpoint);
605 int target_get_gdb_reg_list(struct target_s *target,
606 struct reg_s **reg_list[], int *reg_list_size)
608 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
610 int target_step(struct target_s *target,
611 int current, uint32_t address, int handle_breakpoints)
613 return target->type->step(target, current, address, handle_breakpoints);
617 int target_run_algorithm(struct target_s *target,
618 int num_mem_params, mem_param_t *mem_params,
619 int num_reg_params, reg_param_t *reg_param,
620 uint32_t entry_point, uint32_t exit_point,
621 int timeout_ms, void *arch_info)
623 return target->type->run_algorithm(target,
624 num_mem_params, mem_params, num_reg_params, reg_param,
625 entry_point, exit_point, timeout_ms, arch_info);
628 /// @returns @c true if the target has been examined.
629 bool target_was_examined(struct target_s *target)
631 return target->type->examined;
633 /// Sets the @c examined flag for the given target.
634 void target_set_examined(struct target_s *target)
636 target->type->examined = true;
638 // Reset the @c examined flag for the given target.
639 void target_reset_examined(struct target_s *target)
641 target->type->examined = false;
645 int target_init(struct command_context_s *cmd_ctx)
647 target_t *target = all_targets;
652 target_reset_examined(target);
653 if (target->type->examine == NULL)
655 target->type->examine = default_examine;
658 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
660 LOG_ERROR("target '%s' init failed", target_get_name(target));
664 /* Set up default functions if none are provided by target */
665 if (target->type->virt2phys == NULL)
667 target->type->virt2phys = default_virt2phys;
669 target->type->virt2phys = default_virt2phys;
670 /* a non-invasive way(in terms of patches) to add some code that
671 * runs before the type->write/read_memory implementation
673 target->type->write_memory_imp = target->type->write_memory;
674 target->type->write_memory = target_write_memory_imp;
675 target->type->read_memory_imp = target->type->read_memory;
676 target->type->read_memory = target_read_memory_imp;
677 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
678 target->type->soft_reset_halt = target_soft_reset_halt_imp;
679 target->type->run_algorithm_imp = target->type->run_algorithm;
680 target->type->run_algorithm = target_run_algorithm_imp;
682 if (target->type->mmu == NULL)
684 target->type->mmu = default_mmu;
686 target = target->next;
691 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
693 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
700 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
702 target_event_callback_t **callbacks_p = &target_event_callbacks;
704 if (callback == NULL)
706 return ERROR_INVALID_ARGUMENTS;
711 while ((*callbacks_p)->next)
712 callbacks_p = &((*callbacks_p)->next);
713 callbacks_p = &((*callbacks_p)->next);
716 (*callbacks_p) = malloc(sizeof(target_event_callback_t));
717 (*callbacks_p)->callback = callback;
718 (*callbacks_p)->priv = priv;
719 (*callbacks_p)->next = NULL;
724 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
726 target_timer_callback_t **callbacks_p = &target_timer_callbacks;
729 if (callback == NULL)
731 return ERROR_INVALID_ARGUMENTS;
736 while ((*callbacks_p)->next)
737 callbacks_p = &((*callbacks_p)->next);
738 callbacks_p = &((*callbacks_p)->next);
741 (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
742 (*callbacks_p)->callback = callback;
743 (*callbacks_p)->periodic = periodic;
744 (*callbacks_p)->time_ms = time_ms;
746 gettimeofday(&now, NULL);
747 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
748 time_ms -= (time_ms % 1000);
749 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
750 if ((*callbacks_p)->when.tv_usec > 1000000)
752 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
753 (*callbacks_p)->when.tv_sec += 1;
756 (*callbacks_p)->priv = priv;
757 (*callbacks_p)->next = NULL;
762 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
764 target_event_callback_t **p = &target_event_callbacks;
765 target_event_callback_t *c = target_event_callbacks;
767 if (callback == NULL)
769 return ERROR_INVALID_ARGUMENTS;
774 target_event_callback_t *next = c->next;
775 if ((c->callback == callback) && (c->priv == priv))
789 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
791 target_timer_callback_t **p = &target_timer_callbacks;
792 target_timer_callback_t *c = target_timer_callbacks;
794 if (callback == NULL)
796 return ERROR_INVALID_ARGUMENTS;
801 target_timer_callback_t *next = c->next;
802 if ((c->callback == callback) && (c->priv == priv))
816 int target_call_event_callbacks(target_t *target, enum target_event event)
818 target_event_callback_t *callback = target_event_callbacks;
819 target_event_callback_t *next_callback;
821 if (event == TARGET_EVENT_HALTED)
823 /* execute early halted first */
824 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
827 LOG_DEBUG("target event %i (%s)",
829 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
831 target_handle_event(target, event);
835 next_callback = callback->next;
836 callback->callback(target, event, callback->priv);
837 callback = next_callback;
843 static int target_timer_callback_periodic_restart(
844 target_timer_callback_t *cb, struct timeval *now)
846 int time_ms = cb->time_ms;
847 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
848 time_ms -= (time_ms % 1000);
849 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
850 if (cb->when.tv_usec > 1000000)
852 cb->when.tv_usec = cb->when.tv_usec - 1000000;
853 cb->when.tv_sec += 1;
858 static int target_call_timer_callback(target_timer_callback_t *cb,
861 cb->callback(cb->priv);
864 return target_timer_callback_periodic_restart(cb, now);
866 return target_unregister_timer_callback(cb->callback, cb->priv);
869 static int target_call_timer_callbacks_check_time(int checktime)
874 gettimeofday(&now, NULL);
876 target_timer_callback_t *callback = target_timer_callbacks;
879 // cleaning up may unregister and free this callback
880 target_timer_callback_t *next_callback = callback->next;
882 bool call_it = callback->callback &&
883 ((!checktime && callback->periodic) ||
884 now.tv_sec > callback->when.tv_sec ||
885 (now.tv_sec == callback->when.tv_sec &&
886 now.tv_usec >= callback->when.tv_usec));
890 int retval = target_call_timer_callback(callback, &now);
891 if (retval != ERROR_OK)
895 callback = next_callback;
901 int target_call_timer_callbacks(void)
903 return target_call_timer_callbacks_check_time(1);
906 /* invoke periodic callbacks immediately */
907 int target_call_timer_callbacks_now(void)
909 return target_call_timer_callbacks_check_time(0);
912 int target_alloc_working_area(struct target_s *target, uint32_t size, working_area_t **area)
914 working_area_t *c = target->working_areas;
915 working_area_t *new_wa = NULL;
917 /* Reevaluate working area address based on MMU state*/
918 if (target->working_areas == NULL)
922 retval = target->type->mmu(target, &enabled);
923 if (retval != ERROR_OK)
929 target->working_area = target->working_area_virt;
933 target->working_area = target->working_area_phys;
937 /* only allocate multiples of 4 byte */
940 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
941 size = (size + 3) & (~3);
944 /* see if there's already a matching working area */
947 if ((c->free) && (c->size == size))
955 /* if not, allocate a new one */
958 working_area_t **p = &target->working_areas;
959 uint32_t first_free = target->working_area;
960 uint32_t free_size = target->working_area_size;
962 LOG_DEBUG("allocating new working area");
964 c = target->working_areas;
967 first_free += c->size;
968 free_size -= c->size;
973 if (free_size < size)
975 LOG_WARNING("not enough working area available(requested %u, free %u)",
976 (unsigned)(size), (unsigned)(free_size));
977 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
980 new_wa = malloc(sizeof(working_area_t));
983 new_wa->address = first_free;
985 if (target->backup_working_area)
988 new_wa->backup = malloc(new_wa->size);
989 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
991 free(new_wa->backup);
998 new_wa->backup = NULL;
1001 /* put new entry in list */
1005 /* mark as used, and return the new (reused) area */
1010 new_wa->user = area;
1015 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
1020 if (restore && target->backup_working_area)
1023 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1029 /* mark user pointer invalid */
1036 int target_free_working_area(struct target_s *target, working_area_t *area)
1038 return target_free_working_area_restore(target, area, 1);
1041 /* free resources and restore memory, if restoring memory fails,
1042 * free up resources anyway
1044 void target_free_all_working_areas_restore(struct target_s *target, int restore)
1046 working_area_t *c = target->working_areas;
1050 working_area_t *next = c->next;
1051 target_free_working_area_restore(target, c, restore);
1061 target->working_areas = NULL;
1064 void target_free_all_working_areas(struct target_s *target)
1066 target_free_all_working_areas_restore(target, 1);
1069 int target_register_commands(struct command_context_s *cmd_ctx)
1072 register_command(cmd_ctx, NULL, "targets", handle_targets_command, COMMAND_EXEC, "change the current command line target (one parameter) or lists targets (with no parameter)");
1077 register_jim(cmd_ctx, "target", jim_target, "configure target");
1082 int target_arch_state(struct target_s *target)
1087 LOG_USER("No target has been configured");
1091 LOG_USER("target state: %s", target_state_name( target ));
1093 if (target->state != TARGET_HALTED)
1096 retval = target->type->arch_state(target);
1100 /* Single aligned words are guaranteed to use 16 or 32 bit access
1101 * mode respectively, otherwise data is handled as quickly as
1104 int target_write_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1107 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1108 (int)size, (unsigned)address);
1110 if (!target_was_examined(target))
1112 LOG_ERROR("Target not examined yet");
1120 if ((address + size - 1) < address)
1122 /* GDB can request this when e.g. PC is 0xfffffffc*/
1123 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1129 if (((address % 2) == 0) && (size == 2))
1131 return target_write_memory(target, address, 2, 1, buffer);
1134 /* handle unaligned head bytes */
1137 uint32_t unaligned = 4 - (address % 4);
1139 if (unaligned > size)
1142 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1145 buffer += unaligned;
1146 address += unaligned;
1150 /* handle aligned words */
1153 int aligned = size - (size % 4);
1155 /* use bulk writes above a certain limit. This may have to be changed */
1158 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1163 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1172 /* handle tail writes of less than 4 bytes */
1175 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1182 /* Single aligned words are guaranteed to use 16 or 32 bit access
1183 * mode respectively, otherwise data is handled as quickly as
1186 int target_read_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1189 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1190 (int)size, (unsigned)address);
1192 if (!target_was_examined(target))
1194 LOG_ERROR("Target not examined yet");
1202 if ((address + size - 1) < address)
1204 /* GDB can request this when e.g. PC is 0xfffffffc*/
1205 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1211 if (((address % 2) == 0) && (size == 2))
1213 return target_read_memory(target, address, 2, 1, buffer);
1216 /* handle unaligned head bytes */
1219 uint32_t unaligned = 4 - (address % 4);
1221 if (unaligned > size)
1224 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1227 buffer += unaligned;
1228 address += unaligned;
1232 /* handle aligned words */
1235 int aligned = size - (size % 4);
1237 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1245 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1248 int aligned = size - (size%2);
1249 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1250 if (retval != ERROR_OK)
1257 /* handle tail writes of less than 4 bytes */
1260 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1267 int target_checksum_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* crc)
1272 uint32_t checksum = 0;
1273 if (!target_was_examined(target))
1275 LOG_ERROR("Target not examined yet");
1279 if ((retval = target->type->checksum_memory(target, address,
1280 size, &checksum)) != ERROR_OK)
1282 buffer = malloc(size);
1285 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1286 return ERROR_INVALID_ARGUMENTS;
1288 retval = target_read_buffer(target, address, size, buffer);
1289 if (retval != ERROR_OK)
1295 /* convert to target endianess */
1296 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1298 uint32_t target_data;
1299 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1300 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1303 retval = image_calculate_checksum(buffer, size, &checksum);
1312 int target_blank_check_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* blank)
1315 if (!target_was_examined(target))
1317 LOG_ERROR("Target not examined yet");
1321 if (target->type->blank_check_memory == 0)
1322 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1324 retval = target->type->blank_check_memory(target, address, size, blank);
1329 int target_read_u32(struct target_s *target, uint32_t address, uint32_t *value)
1331 uint8_t value_buf[4];
1332 if (!target_was_examined(target))
1334 LOG_ERROR("Target not examined yet");
1338 int retval = target_read_memory(target, address, 4, 1, value_buf);
1340 if (retval == ERROR_OK)
1342 *value = target_buffer_get_u32(target, value_buf);
1343 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1350 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1357 int target_read_u16(struct target_s *target, uint32_t address, uint16_t *value)
1359 uint8_t value_buf[2];
1360 if (!target_was_examined(target))
1362 LOG_ERROR("Target not examined yet");
1366 int retval = target_read_memory(target, address, 2, 1, value_buf);
1368 if (retval == ERROR_OK)
1370 *value = target_buffer_get_u16(target, value_buf);
1371 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1378 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1385 int target_read_u8(struct target_s *target, uint32_t address, uint8_t *value)
1387 int retval = target_read_memory(target, address, 1, 1, value);
1388 if (!target_was_examined(target))
1390 LOG_ERROR("Target not examined yet");
1394 if (retval == ERROR_OK)
1396 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1403 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1410 int target_write_u32(struct target_s *target, uint32_t address, uint32_t value)
1413 uint8_t value_buf[4];
1414 if (!target_was_examined(target))
1416 LOG_ERROR("Target not examined yet");
1420 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1424 target_buffer_set_u32(target, value_buf, value);
1425 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1427 LOG_DEBUG("failed: %i", retval);
1433 int target_write_u16(struct target_s *target, uint32_t address, uint16_t value)
1436 uint8_t value_buf[2];
1437 if (!target_was_examined(target))
1439 LOG_ERROR("Target not examined yet");
1443 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1447 target_buffer_set_u16(target, value_buf, value);
1448 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1450 LOG_DEBUG("failed: %i", retval);
1456 int target_write_u8(struct target_s *target, uint32_t address, uint8_t value)
1459 if (!target_was_examined(target))
1461 LOG_ERROR("Target not examined yet");
1465 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1468 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1470 LOG_DEBUG("failed: %i", retval);
1476 int target_register_user_commands(struct command_context_s *cmd_ctx)
1478 int retval = ERROR_OK;
1481 /* script procedures */
1482 register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "profiling samples the CPU PC");
1483 register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array, "read memory and return as a TCL array for script processing <ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
1484 register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem, "convert a TCL array to memory locations and write the values <ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
1486 register_command(cmd_ctx, NULL, "fast_load_image", handle_fast_load_image_command, COMMAND_ANY,
1487 "same args as load_image, image stored in memory - mainly for profiling purposes");
1489 register_command(cmd_ctx, NULL, "fast_load", handle_fast_load_command, COMMAND_ANY,
1490 "loads active fast load image to current target - mainly for profiling purposes");
1493 register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "translate a virtual address into a physical address");
1494 register_command(cmd_ctx, NULL, "reg", handle_reg_command, COMMAND_EXEC, "display or set a register");
1495 register_command(cmd_ctx, NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1496 register_command(cmd_ctx, NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1497 register_command(cmd_ctx, NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1498 register_command(cmd_ctx, NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1499 register_command(cmd_ctx, NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1500 register_command(cmd_ctx, NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run | halt | init] - default is run");
1501 register_command(cmd_ctx, NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1503 register_command(cmd_ctx, NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words <addr> [count]");
1504 register_command(cmd_ctx, NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words <addr> [count]");
1505 register_command(cmd_ctx, NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes <addr> [count]");
1507 register_command(cmd_ctx, NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word <addr> <value> [count]");
1508 register_command(cmd_ctx, NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word <addr> <value> [count]");
1509 register_command(cmd_ctx, NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte <addr> <value> [count]");
1511 register_command(cmd_ctx, NULL, "bp",
1512 handle_bp_command, COMMAND_EXEC,
1513 "list or set breakpoint [<address> <length> [hw]]");
1514 register_command(cmd_ctx, NULL, "rbp",
1515 handle_rbp_command, COMMAND_EXEC,
1516 "remove breakpoint <address>");
1517 register_command(cmd_ctx, NULL, "wp",
1518 handle_wp_command, COMMAND_EXEC,
1519 "list or set watchpoint "
1520 "[<address> <length> <r/w/a> [value] [mask]]");
1521 register_command(cmd_ctx, NULL, "rwp",
1522 handle_rwp_command, COMMAND_EXEC,
1523 "remove watchpoint <address>");
1525 register_command(cmd_ctx, NULL, "load_image", handle_load_image_command, COMMAND_EXEC, "load_image <file> <address> ['bin'|'ihex'|'elf'|'s19'] [min_address] [max_length]");
1526 register_command(cmd_ctx, NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1527 register_command(cmd_ctx, NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1528 register_command(cmd_ctx, NULL, "test_image", handle_test_image_command, COMMAND_EXEC, "test_image <file> [offset] [type]");
1530 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
1532 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
1538 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1540 target_t *target = all_targets;
1544 target = get_target(args[0]);
1545 if (target == NULL) {
1546 command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1549 if (!target->tap->enabled) {
1550 command_print(cmd_ctx,"Target: TAP %s is disabled, "
1551 "can't be the current target\n",
1552 target->tap->dotted_name);
1556 cmd_ctx->current_target = target->target_number;
1561 target = all_targets;
1562 command_print(cmd_ctx, " TargetName Type Endian TapName State ");
1563 command_print(cmd_ctx, "-- ------------------ ---------- ------ ------------------ ------------");
1569 if (target->tap->enabled)
1570 state = target_state_name( target );
1572 state = "tap-disabled";
1574 if (cmd_ctx->current_target == target->target_number)
1577 /* keep columns lined up to match the headers above */
1578 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1579 target->target_number,
1582 target_get_name(target),
1583 Jim_Nvp_value2name_simple(nvp_target_endian,
1584 target->endianness)->name,
1585 target->tap->dotted_name,
1587 target = target->next;
1593 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1595 static int powerDropout;
1596 static int srstAsserted;
1598 static int runPowerRestore;
1599 static int runPowerDropout;
1600 static int runSrstAsserted;
1601 static int runSrstDeasserted;
1603 static int sense_handler(void)
1605 static int prevSrstAsserted = 0;
1606 static int prevPowerdropout = 0;
1609 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1613 powerRestored = prevPowerdropout && !powerDropout;
1616 runPowerRestore = 1;
1619 long long current = timeval_ms();
1620 static long long lastPower = 0;
1621 int waitMore = lastPower + 2000 > current;
1622 if (powerDropout && !waitMore)
1624 runPowerDropout = 1;
1625 lastPower = current;
1628 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1632 srstDeasserted = prevSrstAsserted && !srstAsserted;
1634 static long long lastSrst = 0;
1635 waitMore = lastSrst + 2000 > current;
1636 if (srstDeasserted && !waitMore)
1638 runSrstDeasserted = 1;
1642 if (!prevSrstAsserted && srstAsserted)
1644 runSrstAsserted = 1;
1647 prevSrstAsserted = srstAsserted;
1648 prevPowerdropout = powerDropout;
1650 if (srstDeasserted || powerRestored)
1652 /* Other than logging the event we can't do anything here.
1653 * Issuing a reset is a particularly bad idea as we might
1654 * be inside a reset already.
1661 static void target_call_event_callbacks_all(enum target_event e) {
1663 target = all_targets;
1665 target_call_event_callbacks(target, e);
1666 target = target->next;
1670 /* process target state changes */
1671 int handle_target(void *priv)
1673 int retval = ERROR_OK;
1675 /* we do not want to recurse here... */
1676 static int recursive = 0;
1681 /* danger! running these procedures can trigger srst assertions and power dropouts.
1682 * We need to avoid an infinite loop/recursion here and we do that by
1683 * clearing the flags after running these events.
1685 int did_something = 0;
1686 if (runSrstAsserted)
1688 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1689 Jim_Eval(interp, "srst_asserted");
1692 if (runSrstDeasserted)
1694 Jim_Eval(interp, "srst_deasserted");
1697 if (runPowerDropout)
1699 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1700 Jim_Eval(interp, "power_dropout");
1703 if (runPowerRestore)
1705 Jim_Eval(interp, "power_restore");
1711 /* clear detect flags */
1715 /* clear action flags */
1717 runSrstAsserted = 0;
1718 runSrstDeasserted = 0;
1719 runPowerRestore = 0;
1720 runPowerDropout = 0;
1725 /* Poll targets for state changes unless that's globally disabled.
1726 * Skip targets that are currently disabled.
1728 for (target_t *target = all_targets;
1729 target_continuous_poll && target;
1730 target = target->next)
1732 if (!target->tap->enabled)
1735 /* only poll target if we've got power and srst isn't asserted */
1736 if (!powerDropout && !srstAsserted)
1738 /* polling may fail silently until the target has been examined */
1739 if ((retval = target_poll(target)) != ERROR_OK)
1741 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1750 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1759 target = get_current_target(cmd_ctx);
1761 /* list all available registers for the current target */
1764 reg_cache_t *cache = target->reg_cache;
1771 for (i = 0, reg = cache->reg_list;
1772 i < cache->num_regs;
1773 i++, reg++, count++)
1775 /* only print cached values if they are valid */
1777 value = buf_to_str(reg->value,
1779 command_print(cmd_ctx,
1780 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1788 command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1793 cache = cache->next;
1799 /* access a single register by its ordinal number */
1800 if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1803 int retval = parse_uint(args[0], &num);
1804 if (ERROR_OK != retval)
1805 return ERROR_COMMAND_SYNTAX_ERROR;
1807 reg_cache_t *cache = target->reg_cache;
1812 for (i = 0; i < cache->num_regs; i++)
1814 if (count++ == (int)num)
1816 reg = &cache->reg_list[i];
1822 cache = cache->next;
1827 command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1830 } else /* access a single register by its name */
1832 reg = register_get_by_name(target->reg_cache, args[0], 1);
1836 command_print(cmd_ctx, "register %s not found in current target", args[0]);
1841 /* display a register */
1842 if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1844 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1847 if (reg->valid == 0)
1849 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1850 arch_type->get(reg);
1852 value = buf_to_str(reg->value, reg->size, 16);
1853 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1858 /* set register value */
1861 uint8_t *buf = malloc(CEIL(reg->size, 8));
1862 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1864 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1865 arch_type->set(reg, buf);
1867 value = buf_to_str(reg->value, reg->size, 16);
1868 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1876 command_print(cmd_ctx, "usage: reg <#|name> [value]");
1881 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1883 int retval = ERROR_OK;
1884 target_t *target = get_current_target(cmd_ctx);
1888 command_print(cmd_ctx, "background polling: %s",
1889 target_continuous_poll ? "on" : "off");
1890 command_print(cmd_ctx, "TAP: %s (%s)",
1891 target->tap->dotted_name,
1892 target->tap->enabled ? "enabled" : "disabled");
1893 if (!target->tap->enabled)
1895 if ((retval = target_poll(target)) != ERROR_OK)
1897 if ((retval = target_arch_state(target)) != ERROR_OK)
1903 if (strcmp(args[0], "on") == 0)
1905 target_continuous_poll = 1;
1907 else if (strcmp(args[0], "off") == 0)
1909 target_continuous_poll = 0;
1913 command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1917 return ERROR_COMMAND_SYNTAX_ERROR;
1923 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1926 return ERROR_COMMAND_SYNTAX_ERROR;
1931 int retval = parse_uint(args[0], &ms);
1932 if (ERROR_OK != retval)
1934 command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1935 return ERROR_COMMAND_SYNTAX_ERROR;
1937 // convert seconds (given) to milliseconds (needed)
1941 target_t *target = get_current_target(cmd_ctx);
1942 return target_wait_state(target, TARGET_HALTED, ms);
1945 /* wait for target state to change. The trick here is to have a low
1946 * latency for short waits and not to suck up all the CPU time
1949 * After 500ms, keep_alive() is invoked
1951 int target_wait_state(target_t *target, enum target_state state, int ms)
1954 long long then = 0, cur;
1959 if ((retval = target_poll(target)) != ERROR_OK)
1961 if (target->state == state)
1969 then = timeval_ms();
1970 LOG_DEBUG("waiting for target %s...",
1971 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1979 if ((cur-then) > ms)
1981 LOG_ERROR("timed out while waiting for target %s",
1982 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1990 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1994 target_t *target = get_current_target(cmd_ctx);
1995 int retval = target_halt(target);
1996 if (ERROR_OK != retval)
2002 retval = parse_uint(args[0], &wait);
2003 if (ERROR_OK != retval)
2004 return ERROR_COMMAND_SYNTAX_ERROR;
2009 return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
2012 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2014 target_t *target = get_current_target(cmd_ctx);
2016 LOG_USER("requesting target halt and executing a soft reset");
2018 target->type->soft_reset_halt(target);
2023 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2026 return ERROR_COMMAND_SYNTAX_ERROR;
2028 enum target_reset_mode reset_mode = RESET_RUN;
2032 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2033 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2034 return ERROR_COMMAND_SYNTAX_ERROR;
2036 reset_mode = n->value;
2039 /* reset *all* targets */
2040 return target_process_reset(cmd_ctx, reset_mode);
2044 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2048 return ERROR_COMMAND_SYNTAX_ERROR;
2050 target_t *target = get_current_target(cmd_ctx);
2051 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2053 /* with no args, resume from current pc, addr = 0,
2054 * with one arguments, addr = args[0],
2055 * handle breakpoints, not debugging */
2059 int retval = parse_u32(args[0], &addr);
2060 if (ERROR_OK != retval)
2065 return target_resume(target, current, addr, 1, 0);
2068 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2071 return ERROR_COMMAND_SYNTAX_ERROR;
2075 /* with no args, step from current pc, addr = 0,
2076 * with one argument addr = args[0],
2077 * handle breakpoints, debugging */
2082 int retval = parse_u32(args[0], &addr);
2083 if (ERROR_OK != retval)
2088 target_t *target = get_current_target(cmd_ctx);
2090 return target->type->step(target, current_pc, addr, 1);
2093 static void handle_md_output(struct command_context_s *cmd_ctx,
2094 struct target_s *target, uint32_t address, unsigned size,
2095 unsigned count, const uint8_t *buffer)
2097 const unsigned line_bytecnt = 32;
2098 unsigned line_modulo = line_bytecnt / size;
2100 char output[line_bytecnt * 4 + 1];
2101 unsigned output_len = 0;
2103 const char *value_fmt;
2105 case 4: value_fmt = "%8.8x "; break;
2106 case 2: value_fmt = "%4.2x "; break;
2107 case 1: value_fmt = "%2.2x "; break;
2109 LOG_ERROR("invalid memory read size: %u", size);
2113 for (unsigned i = 0; i < count; i++)
2115 if (i % line_modulo == 0)
2117 output_len += snprintf(output + output_len,
2118 sizeof(output) - output_len,
2120 (unsigned)(address + (i*size)));
2124 const uint8_t *value_ptr = buffer + i * size;
2126 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2127 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2128 case 1: value = *value_ptr;
2130 output_len += snprintf(output + output_len,
2131 sizeof(output) - output_len,
2134 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2136 command_print(cmd_ctx, "%s", output);
2142 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2145 return ERROR_COMMAND_SYNTAX_ERROR;
2149 case 'w': size = 4; break;
2150 case 'h': size = 2; break;
2151 case 'b': size = 1; break;
2152 default: return ERROR_COMMAND_SYNTAX_ERROR;
2156 int retval = parse_u32(args[0], &address);
2157 if (ERROR_OK != retval)
2163 retval = parse_uint(args[1], &count);
2164 if (ERROR_OK != retval)
2168 uint8_t *buffer = calloc(count, size);
2170 target_t *target = get_current_target(cmd_ctx);
2171 retval = target_read_memory(target,
2172 address, size, count, buffer);
2173 if (ERROR_OK == retval)
2174 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2181 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2183 if ((argc < 2) || (argc > 3))
2184 return ERROR_COMMAND_SYNTAX_ERROR;
2187 int retval = parse_u32(args[0], &address);
2188 if (ERROR_OK != retval)
2192 retval = parse_u32(args[1], &value);
2193 if (ERROR_OK != retval)
2199 retval = parse_uint(args[2], &count);
2200 if (ERROR_OK != retval)
2204 target_t *target = get_current_target(cmd_ctx);
2206 uint8_t value_buf[4];
2211 target_buffer_set_u32(target, value_buf, value);
2215 target_buffer_set_u16(target, value_buf, value);
2219 value_buf[0] = value;
2222 return ERROR_COMMAND_SYNTAX_ERROR;
2224 for (unsigned i = 0; i < count; i++)
2226 retval = target_write_memory(target,
2227 address + i * wordsize, wordsize, 1, value_buf);
2228 if (ERROR_OK != retval)
2237 static int parse_load_image_command_args(char **args, int argc,
2238 image_t *image, uint32_t *min_address, uint32_t *max_address)
2240 if (argc < 1 || argc > 5)
2241 return ERROR_COMMAND_SYNTAX_ERROR;
2243 /* a base address isn't always necessary,
2244 * default to 0x0 (i.e. don't relocate) */
2248 int retval = parse_u32(args[1], &addr);
2249 if (ERROR_OK != retval)
2250 return ERROR_COMMAND_SYNTAX_ERROR;
2251 image->base_address = addr;
2252 image->base_address_set = 1;
2255 image->base_address_set = 0;
2257 image->start_address_set = 0;
2261 int retval = parse_u32(args[3], min_address);
2262 if (ERROR_OK != retval)
2263 return ERROR_COMMAND_SYNTAX_ERROR;
2267 int retval = parse_u32(args[4], max_address);
2268 if (ERROR_OK != retval)
2269 return ERROR_COMMAND_SYNTAX_ERROR;
2270 // use size (given) to find max (required)
2271 *max_address += *min_address;
2274 if (*min_address > *max_address)
2275 return ERROR_COMMAND_SYNTAX_ERROR;
2280 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2284 uint32_t image_size;
2285 uint32_t min_address = 0;
2286 uint32_t max_address = 0xffffffff;
2292 duration_t duration;
2293 char *duration_text;
2295 int retval = parse_load_image_command_args(args, argc,
2296 &image, &min_address, &max_address);
2297 if (ERROR_OK != retval)
2300 target_t *target = get_current_target(cmd_ctx);
2301 duration_start_measure(&duration);
2303 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2310 for (i = 0; i < image.num_sections; i++)
2312 buffer = malloc(image.sections[i].size);
2315 command_print(cmd_ctx,
2316 "error allocating buffer for section (%d bytes)",
2317 (int)(image.sections[i].size));
2321 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2327 uint32_t offset = 0;
2328 uint32_t length = buf_cnt;
2330 /* DANGER!!! beware of unsigned comparision here!!! */
2332 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2333 (image.sections[i].base_address < max_address))
2335 if (image.sections[i].base_address < min_address)
2337 /* clip addresses below */
2338 offset += min_address-image.sections[i].base_address;
2342 if (image.sections[i].base_address + buf_cnt > max_address)
2344 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2347 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2352 image_size += length;
2353 command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2354 (unsigned int)length,
2355 image.sections[i].base_address + offset);
2361 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2363 image_close(&image);
2367 if (retval == ERROR_OK)
2369 command_print(cmd_ctx, "downloaded %u byte in %s",
2370 (unsigned int)image_size,
2373 free(duration_text);
2375 image_close(&image);
2381 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2385 uint8_t buffer[560];
2388 duration_t duration;
2389 char *duration_text;
2391 target_t *target = get_current_target(cmd_ctx);
2395 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2400 int retval = parse_u32(args[1], &address);
2401 if (ERROR_OK != retval)
2405 retval = parse_u32(args[2], &size);
2406 if (ERROR_OK != retval)
2409 if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2414 duration_start_measure(&duration);
2418 uint32_t size_written;
2419 uint32_t this_run_size = (size > 560) ? 560 : size;
2421 retval = target_read_buffer(target, address, this_run_size, buffer);
2422 if (retval != ERROR_OK)
2427 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2428 if (retval != ERROR_OK)
2433 size -= this_run_size;
2434 address += this_run_size;
2437 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2440 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2443 if (retval == ERROR_OK)
2445 command_print(cmd_ctx, "dumped %lld byte in %s",
2446 fileio.size, duration_text);
2447 free(duration_text);
2453 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2457 uint32_t image_size;
2459 int retval, retvaltemp;
2460 uint32_t checksum = 0;
2461 uint32_t mem_checksum = 0;
2465 duration_t duration;
2466 char *duration_text;
2468 target_t *target = get_current_target(cmd_ctx);
2472 return ERROR_COMMAND_SYNTAX_ERROR;
2477 LOG_ERROR("no target selected");
2481 duration_start_measure(&duration);
2486 retval = parse_u32(args[1], &addr);
2487 if (ERROR_OK != retval)
2488 return ERROR_COMMAND_SYNTAX_ERROR;
2489 image.base_address = addr;
2490 image.base_address_set = 1;
2494 image.base_address_set = 0;
2495 image.base_address = 0x0;
2498 image.start_address_set = 0;
2500 if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2507 for (i = 0; i < image.num_sections; i++)
2509 buffer = malloc(image.sections[i].size);
2512 command_print(cmd_ctx,
2513 "error allocating buffer for section (%d bytes)",
2514 (int)(image.sections[i].size));
2517 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2525 /* calculate checksum of image */
2526 image_calculate_checksum(buffer, buf_cnt, &checksum);
2528 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2529 if (retval != ERROR_OK)
2535 if (checksum != mem_checksum)
2537 /* failed crc checksum, fall back to a binary compare */
2540 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2542 data = (uint8_t*)malloc(buf_cnt);
2544 /* Can we use 32bit word accesses? */
2546 int count = buf_cnt;
2547 if ((count % 4) == 0)
2552 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2553 if (retval == ERROR_OK)
2556 for (t = 0; t < buf_cnt; t++)
2558 if (data[t] != buffer[t])
2560 command_print(cmd_ctx,
2561 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2562 (unsigned)(t + image.sections[i].base_address),
2567 retval = ERROR_FAIL;
2581 command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2582 image.sections[i].base_address,
2587 image_size += buf_cnt;
2591 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2593 image_close(&image);
2597 if (retval == ERROR_OK)
2599 command_print(cmd_ctx, "verified %u bytes in %s",
2600 (unsigned int)image_size,
2603 free(duration_text);
2605 image_close(&image);
2610 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2612 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2615 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2617 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2620 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2622 target_t *target = get_current_target(cmd_ctx);
2623 breakpoint_t *breakpoint = target->breakpoints;
2626 if (breakpoint->type == BKPT_SOFT)
2628 char* buf = buf_to_str(breakpoint->orig_instr,
2629 breakpoint->length, 16);
2630 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2631 breakpoint->address,
2633 breakpoint->set, buf);
2638 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2639 breakpoint->address,
2640 breakpoint->length, breakpoint->set);
2643 breakpoint = breakpoint->next;
2648 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2649 uint32_t addr, uint32_t length, int hw)
2651 target_t *target = get_current_target(cmd_ctx);
2652 int retval = breakpoint_add(target, addr, length, hw);
2653 if (ERROR_OK == retval)
2654 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2656 LOG_ERROR("Failure setting breakpoint");
2660 static int handle_bp_command(struct command_context_s *cmd_ctx,
2661 char *cmd, char **args, int argc)
2664 return handle_bp_command_list(cmd_ctx);
2666 if (argc < 2 || argc > 3)
2668 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2669 return ERROR_COMMAND_SYNTAX_ERROR;
2673 int retval = parse_u32(args[0], &addr);
2674 if (ERROR_OK != retval)
2678 retval = parse_u32(args[1], &length);
2679 if (ERROR_OK != retval)
2685 if (strcmp(args[2], "hw") == 0)
2688 return ERROR_COMMAND_SYNTAX_ERROR;
2691 return handle_bp_command_set(cmd_ctx, addr, length, hw);
2694 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2697 return ERROR_COMMAND_SYNTAX_ERROR;
2700 int retval = parse_u32(args[0], &addr);
2701 if (ERROR_OK != retval)
2704 target_t *target = get_current_target(cmd_ctx);
2705 breakpoint_remove(target, addr);
2710 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2712 target_t *target = get_current_target(cmd_ctx);
2716 watchpoint_t *watchpoint = target->watchpoints;
2720 command_print(cmd_ctx,
2721 "address: 0x%8.8" PRIx32 ", len: 0x%8.8x, r/w/a: %i, value: 0x%8.8" PRIx32 ", mask: 0x%8.8" PRIx32 "",
2722 watchpoint->address,
2724 (int)(watchpoint->rw),
2727 watchpoint = watchpoint->next;
2732 enum watchpoint_rw type = WPT_ACCESS;
2734 uint32_t length = 0;
2735 uint32_t data_value = 0x0;
2736 uint32_t data_mask = 0xffffffff;
2742 retval = parse_u32(args[4], &data_mask);
2743 if (ERROR_OK != retval)
2747 retval = parse_u32(args[3], &data_value);
2748 if (ERROR_OK != retval)
2764 LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2765 return ERROR_COMMAND_SYNTAX_ERROR;
2769 retval = parse_u32(args[1], &length);
2770 if (ERROR_OK != retval)
2772 retval = parse_u32(args[0], &addr);
2773 if (ERROR_OK != retval)
2778 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2779 return ERROR_COMMAND_SYNTAX_ERROR;
2782 retval = watchpoint_add(target, addr, length, type,
2783 data_value, data_mask);
2784 if (ERROR_OK != retval)
2785 LOG_ERROR("Failure setting watchpoints");
2790 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2793 return ERROR_COMMAND_SYNTAX_ERROR;
2796 int retval = parse_u32(args[0], &addr);
2797 if (ERROR_OK != retval)
2800 target_t *target = get_current_target(cmd_ctx);
2801 watchpoint_remove(target, addr);
2808 * Translate a virtual address to a physical address.
2810 * The low-level target implementation must have logged a detailed error
2811 * which is forwarded to telnet/GDB session.
2813 static int handle_virt2phys_command(command_context_t *cmd_ctx,
2814 char *cmd, char **args, int argc)
2817 return ERROR_COMMAND_SYNTAX_ERROR;
2820 int retval = parse_u32(args[0], &va);
2821 if (ERROR_OK != retval)
2825 target_t *target = get_current_target(cmd_ctx);
2826 retval = target->type->virt2phys(target, va, &pa);
2827 if (retval == ERROR_OK)
2828 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2833 static void writeData(FILE *f, const void *data, size_t len)
2835 size_t written = fwrite(data, 1, len, f);
2837 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2840 static void writeLong(FILE *f, int l)
2843 for (i = 0; i < 4; i++)
2845 char c = (l >> (i*8))&0xff;
2846 writeData(f, &c, 1);
2851 static void writeString(FILE *f, char *s)
2853 writeData(f, s, strlen(s));
2856 /* Dump a gmon.out histogram file. */
2857 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
2860 FILE *f = fopen(filename, "w");
2863 writeString(f, "gmon");
2864 writeLong(f, 0x00000001); /* Version */
2865 writeLong(f, 0); /* padding */
2866 writeLong(f, 0); /* padding */
2867 writeLong(f, 0); /* padding */
2869 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2870 writeData(f, &zero, 1);
2872 /* figure out bucket size */
2873 uint32_t min = samples[0];
2874 uint32_t max = samples[0];
2875 for (i = 0; i < sampleNum; i++)
2877 if (min > samples[i])
2881 if (max < samples[i])
2887 int addressSpace = (max-min + 1);
2889 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2890 uint32_t length = addressSpace;
2891 if (length > maxBuckets)
2893 length = maxBuckets;
2895 int *buckets = malloc(sizeof(int)*length);
2896 if (buckets == NULL)
2901 memset(buckets, 0, sizeof(int)*length);
2902 for (i = 0; i < sampleNum;i++)
2904 uint32_t address = samples[i];
2905 long long a = address-min;
2906 long long b = length-1;
2907 long long c = addressSpace-1;
2908 int index = (a*b)/c; /* danger!!!! int32 overflows */
2912 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2913 writeLong(f, min); /* low_pc */
2914 writeLong(f, max); /* high_pc */
2915 writeLong(f, length); /* # of samples */
2916 writeLong(f, 64000000); /* 64MHz */
2917 writeString(f, "seconds");
2918 for (i = 0; i < (15-strlen("seconds")); i++)
2919 writeData(f, &zero, 1);
2920 writeString(f, "s");
2922 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2924 char *data = malloc(2*length);
2927 for (i = 0; i < length;i++)
2936 data[i*2 + 1]=(val >> 8)&0xff;
2939 writeData(f, data, length * 2);
2949 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2950 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2952 target_t *target = get_current_target(cmd_ctx);
2953 struct timeval timeout, now;
2955 gettimeofday(&timeout, NULL);
2958 return ERROR_COMMAND_SYNTAX_ERROR;
2961 int retval = parse_uint(args[0], &offset);
2962 if (ERROR_OK != retval)
2965 timeval_add_time(&timeout, offset, 0);
2967 command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
2969 static const int maxSample = 10000;
2970 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
2971 if (samples == NULL)
2975 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2976 reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
2980 target_poll(target);
2981 if (target->state == TARGET_HALTED)
2983 uint32_t t=*((uint32_t *)reg->value);
2984 samples[numSamples++]=t;
2985 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2986 target_poll(target);
2987 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2988 } else if (target->state == TARGET_RUNNING)
2990 /* We want to quickly sample the PC. */
2991 if ((retval = target_halt(target)) != ERROR_OK)
2998 command_print(cmd_ctx, "Target not halted or running");
3002 if (retval != ERROR_OK)
3007 gettimeofday(&now, NULL);
3008 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3010 command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3011 if ((retval = target_poll(target)) != ERROR_OK)
3016 if (target->state == TARGET_HALTED)
3018 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3020 if ((retval = target_poll(target)) != ERROR_OK)
3025 writeGmon(samples, numSamples, args[1]);
3026 command_print(cmd_ctx, "Wrote %s", args[1]);
3035 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3038 Jim_Obj *nameObjPtr, *valObjPtr;
3041 namebuf = alloc_printf("%s(%d)", varname, idx);
3045 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3046 valObjPtr = Jim_NewIntObj(interp, val);
3047 if (!nameObjPtr || !valObjPtr)
3053 Jim_IncrRefCount(nameObjPtr);
3054 Jim_IncrRefCount(valObjPtr);
3055 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3056 Jim_DecrRefCount(interp, nameObjPtr);
3057 Jim_DecrRefCount(interp, valObjPtr);
3059 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3063 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3065 command_context_t *context;
3068 context = Jim_GetAssocData(interp, "context");
3069 if (context == NULL)
3071 LOG_ERROR("mem2array: no command context");
3074 target = get_current_target(context);
3077 LOG_ERROR("mem2array: no current target");
3081 return target_mem2array(interp, target, argc-1, argv + 1);
3084 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3092 const char *varname;
3093 uint8_t buffer[4096];
3097 /* argv[1] = name of array to receive the data
3098 * argv[2] = desired width
3099 * argv[3] = memory address
3100 * argv[4] = count of times to read
3103 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3106 varname = Jim_GetString(argv[0], &len);
3107 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3109 e = Jim_GetLong(interp, argv[1], &l);
3115 e = Jim_GetLong(interp, argv[2], &l);
3120 e = Jim_GetLong(interp, argv[3], &l);
3136 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3137 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3141 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3142 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3145 if ((addr + (len * width)) < addr) {
3146 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3147 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3150 /* absurd transfer size? */
3152 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3153 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3158 ((width == 2) && ((addr & 1) == 0)) ||
3159 ((width == 4) && ((addr & 3) == 0))) {
3163 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3164 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3167 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3178 /* Slurp... in buffer size chunks */
3180 count = len; /* in objects.. */
3181 if (count > (sizeof(buffer)/width)) {
3182 count = (sizeof(buffer)/width);
3185 retval = target_read_memory(target, addr, width, count, buffer);
3186 if (retval != ERROR_OK) {
3188 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3192 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3193 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3197 v = 0; /* shut up gcc */
3198 for (i = 0 ;i < count ;i++, n++) {
3201 v = target_buffer_get_u32(target, &buffer[i*width]);
3204 v = target_buffer_get_u16(target, &buffer[i*width]);
3207 v = buffer[i] & 0x0ff;
3210 new_int_array_element(interp, varname, n, v);
3216 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3221 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3224 Jim_Obj *nameObjPtr, *valObjPtr;
3228 namebuf = alloc_printf("%s(%d)", varname, idx);
3232 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3239 Jim_IncrRefCount(nameObjPtr);
3240 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3241 Jim_DecrRefCount(interp, nameObjPtr);
3243 if (valObjPtr == NULL)
3246 result = Jim_GetLong(interp, valObjPtr, &l);
3247 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3252 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3254 command_context_t *context;
3257 context = Jim_GetAssocData(interp, "context");
3258 if (context == NULL) {
3259 LOG_ERROR("array2mem: no command context");
3262 target = get_current_target(context);
3263 if (target == NULL) {
3264 LOG_ERROR("array2mem: no current target");
3268 return target_array2mem(interp,target, argc-1, argv + 1);
3271 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3279 const char *varname;
3280 uint8_t buffer[4096];
3284 /* argv[1] = name of array to get the data
3285 * argv[2] = desired width
3286 * argv[3] = memory address
3287 * argv[4] = count to write
3290 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3293 varname = Jim_GetString(argv[0], &len);
3294 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3296 e = Jim_GetLong(interp, argv[1], &l);
3302 e = Jim_GetLong(interp, argv[2], &l);
3307 e = Jim_GetLong(interp, argv[3], &l);
3323 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3324 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3328 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3329 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3332 if ((addr + (len * width)) < addr) {
3333 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3334 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3337 /* absurd transfer size? */
3339 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3340 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3345 ((width == 2) && ((addr & 1) == 0)) ||
3346 ((width == 4) && ((addr & 3) == 0))) {
3350 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3351 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3354 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3365 /* Slurp... in buffer size chunks */
3367 count = len; /* in objects.. */
3368 if (count > (sizeof(buffer)/width)) {
3369 count = (sizeof(buffer)/width);
3372 v = 0; /* shut up gcc */
3373 for (i = 0 ;i < count ;i++, n++) {
3374 get_int_array_element(interp, varname, n, &v);
3377 target_buffer_set_u32(target, &buffer[i*width], v);
3380 target_buffer_set_u16(target, &buffer[i*width], v);
3383 buffer[i] = v & 0x0ff;
3389 retval = target_write_memory(target, addr, width, count, buffer);
3390 if (retval != ERROR_OK) {
3392 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3396 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3397 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3403 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3408 void target_all_handle_event(enum target_event e)
3412 LOG_DEBUG("**all*targets: event: %d, %s",
3414 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3416 target = all_targets;
3418 target_handle_event(target, e);
3419 target = target->next;
3423 void target_handle_event(target_t *target, enum target_event e)
3425 target_event_action_t *teap;
3427 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3428 if (teap->event == e) {
3429 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3430 target->target_number,
3432 target_get_name(target),
3434 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3435 Jim_GetString(teap->body, NULL));
3436 if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3438 Jim_PrintErrorMessage(interp);
3444 enum target_cfg_param {
3447 TCFG_WORK_AREA_VIRT,
3448 TCFG_WORK_AREA_PHYS,
3449 TCFG_WORK_AREA_SIZE,
3450 TCFG_WORK_AREA_BACKUP,
3453 TCFG_CHAIN_POSITION,
3456 static Jim_Nvp nvp_config_opts[] = {
3457 { .name = "-type", .value = TCFG_TYPE },
3458 { .name = "-event", .value = TCFG_EVENT },
3459 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3460 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3461 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3462 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3463 { .name = "-endian" , .value = TCFG_ENDIAN },
3464 { .name = "-variant", .value = TCFG_VARIANT },
3465 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3467 { .name = NULL, .value = -1 }
3470 static int target_configure(Jim_GetOptInfo *goi, target_t *target)
3478 /* parse config or cget options ... */
3479 while (goi->argc > 0) {
3480 Jim_SetEmptyResult(goi->interp);
3481 /* Jim_GetOpt_Debug(goi); */
3483 if (target->type->target_jim_configure) {
3484 /* target defines a configure function */
3485 /* target gets first dibs on parameters */
3486 e = (*(target->type->target_jim_configure))(target, goi);
3495 /* otherwise we 'continue' below */
3497 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3499 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3505 if (goi->isconfigure) {
3506 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3510 if (goi->argc != 0) {
3511 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3515 Jim_SetResultString(goi->interp, target_get_name(target), -1);
3519 if (goi->argc == 0) {
3520 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3524 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3526 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3530 if (goi->isconfigure) {
3531 if (goi->argc != 1) {
3532 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3536 if (goi->argc != 0) {
3537 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3543 target_event_action_t *teap;
3545 teap = target->event_action;
3546 /* replace existing? */
3548 if (teap->event == (enum target_event)n->value) {
3554 if (goi->isconfigure) {
3555 bool replace = true;
3558 teap = calloc(1, sizeof(*teap));
3561 teap->event = n->value;
3562 Jim_GetOpt_Obj(goi, &o);
3564 Jim_DecrRefCount(interp, teap->body);
3566 teap->body = Jim_DuplicateObj(goi->interp, o);
3569 * Tcl/TK - "tk events" have a nice feature.
3570 * See the "BIND" command.
3571 * We should support that here.
3572 * You can specify %X and %Y in the event code.
3573 * The idea is: %T - target name.
3574 * The idea is: %N - target number
3575 * The idea is: %E - event name.
3577 Jim_IncrRefCount(teap->body);
3581 /* add to head of event list */
3582 teap->next = target->event_action;
3583 target->event_action = teap;
3585 Jim_SetEmptyResult(goi->interp);
3589 Jim_SetEmptyResult(goi->interp);
3591 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3598 case TCFG_WORK_AREA_VIRT:
3599 if (goi->isconfigure) {
3600 target_free_all_working_areas(target);
3601 e = Jim_GetOpt_Wide(goi, &w);
3605 target->working_area_virt = w;
3607 if (goi->argc != 0) {
3611 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3615 case TCFG_WORK_AREA_PHYS:
3616 if (goi->isconfigure) {
3617 target_free_all_working_areas(target);
3618 e = Jim_GetOpt_Wide(goi, &w);
3622 target->working_area_phys = w;
3624 if (goi->argc != 0) {
3628 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3632 case TCFG_WORK_AREA_SIZE:
3633 if (goi->isconfigure) {
3634 target_free_all_working_areas(target);
3635 e = Jim_GetOpt_Wide(goi, &w);
3639 target->working_area_size = w;
3641 if (goi->argc != 0) {
3645 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3649 case TCFG_WORK_AREA_BACKUP:
3650 if (goi->isconfigure) {
3651 target_free_all_working_areas(target);
3652 e = Jim_GetOpt_Wide(goi, &w);
3656 /* make this exactly 1 or 0 */
3657 target->backup_working_area = (!!w);
3659 if (goi->argc != 0) {
3663 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3664 /* loop for more e*/
3668 if (goi->isconfigure) {
3669 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3671 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3674 target->endianness = n->value;
3676 if (goi->argc != 0) {
3680 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3681 if (n->name == NULL) {
3682 target->endianness = TARGET_LITTLE_ENDIAN;
3683 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3685 Jim_SetResultString(goi->interp, n->name, -1);
3690 if (goi->isconfigure) {
3691 if (goi->argc < 1) {
3692 Jim_SetResult_sprintf(goi->interp,
3697 if (target->variant) {
3698 free((void *)(target->variant));
3700 e = Jim_GetOpt_String(goi, &cp, NULL);
3701 target->variant = strdup(cp);
3703 if (goi->argc != 0) {
3707 Jim_SetResultString(goi->interp, target->variant,-1);
3710 case TCFG_CHAIN_POSITION:
3711 if (goi->isconfigure) {
3714 target_free_all_working_areas(target);
3715 e = Jim_GetOpt_Obj(goi, &o);
3719 tap = jtag_tap_by_jim_obj(goi->interp, o);
3723 /* make this exactly 1 or 0 */
3726 if (goi->argc != 0) {
3730 Jim_SetResultString(interp, target->tap->dotted_name, -1);
3731 /* loop for more e*/
3734 } /* while (goi->argc) */
3737 /* done - we return */
3741 /** this is the 'tcl' handler for the target specific command */
3742 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3747 uint8_t target_buf[32];
3750 struct command_context_s *cmd_ctx;
3757 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3758 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3759 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3760 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3768 TS_CMD_INVOKE_EVENT,
3771 static const Jim_Nvp target_options[] = {
3772 { .name = "configure", .value = TS_CMD_CONFIGURE },
3773 { .name = "cget", .value = TS_CMD_CGET },
3774 { .name = "mww", .value = TS_CMD_MWW },
3775 { .name = "mwh", .value = TS_CMD_MWH },
3776 { .name = "mwb", .value = TS_CMD_MWB },
3777 { .name = "mdw", .value = TS_CMD_MDW },
3778 { .name = "mdh", .value = TS_CMD_MDH },
3779 { .name = "mdb", .value = TS_CMD_MDB },
3780 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3781 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3782 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3783 { .name = "curstate", .value = TS_CMD_CURSTATE },
3785 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3786 { .name = "arp_poll", .value = TS_CMD_POLL },
3787 { .name = "arp_reset", .value = TS_CMD_RESET },
3788 { .name = "arp_halt", .value = TS_CMD_HALT },
3789 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3790 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3792 { .name = NULL, .value = -1 },
3795 /* go past the "command" */
3796 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3798 target = Jim_CmdPrivData(goi.interp);
3799 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3801 /* commands here are in an NVP table */
3802 e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3804 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3807 /* Assume blank result */
3808 Jim_SetEmptyResult(goi.interp);
3811 case TS_CMD_CONFIGURE:
3813 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3816 goi.isconfigure = 1;
3817 return target_configure(&goi, target);
3819 // some things take params
3821 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3824 goi.isconfigure = 0;
3825 return target_configure(&goi, target);
3833 * argv[3] = optional count.
3836 if ((goi.argc == 2) || (goi.argc == 3)) {
3840 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3844 e = Jim_GetOpt_Wide(&goi, &a);
3849 e = Jim_GetOpt_Wide(&goi, &b);
3853 if (goi.argc == 3) {
3854 e = Jim_GetOpt_Wide(&goi, &c);
3864 target_buffer_set_u32(target, target_buf, b);
3868 target_buffer_set_u16(target, target_buf, b);
3872 target_buffer_set_u8(target, target_buf, b);
3876 for (x = 0 ; x < c ; x++) {
3877 e = target_write_memory(target, a, b, 1, target_buf);
3878 if (e != ERROR_OK) {
3879 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3892 /* argv[0] = command
3894 * argv[2] = optional count
3896 if ((goi.argc == 2) || (goi.argc == 3)) {
3897 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3900 e = Jim_GetOpt_Wide(&goi, &a);
3905 e = Jim_GetOpt_Wide(&goi, &c);
3912 b = 1; /* shut up gcc */
3925 /* convert to "bytes" */
3927 /* count is now in 'BYTES' */
3933 e = target_read_memory(target, a, b, y / b, target_buf);
3934 if (e != ERROR_OK) {
3935 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
3939 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
3942 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
3943 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
3944 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
3946 for (; (x < 16) ; x += 4) {
3947 Jim_fprintf(interp, interp->cookie_stdout, " ");
3951 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
3952 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
3953 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
3955 for (; (x < 16) ; x += 2) {
3956 Jim_fprintf(interp, interp->cookie_stdout, " ");
3961 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
3962 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
3963 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
3965 for (; (x < 16) ; x += 1) {
3966 Jim_fprintf(interp, interp->cookie_stdout, " ");
3970 /* ascii-ify the bytes */
3971 for (x = 0 ; x < y ; x++) {
3972 if ((target_buf[x] >= 0x20) &&
3973 (target_buf[x] <= 0x7e)) {
3977 target_buf[x] = '.';
3982 target_buf[x] = ' ';
3987 /* print - with a newline */
3988 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
3994 case TS_CMD_MEM2ARRAY:
3995 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
3997 case TS_CMD_ARRAY2MEM:
3998 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4000 case TS_CMD_EXAMINE:
4002 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4005 if (!target->tap->enabled)
4006 goto err_tap_disabled;
4007 e = target->type->examine(target);
4008 if (e != ERROR_OK) {
4009 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4015 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4018 if (!target->tap->enabled)
4019 goto err_tap_disabled;
4020 if (!(target_was_examined(target))) {
4021 e = ERROR_TARGET_NOT_EXAMINED;
4023 e = target->type->poll(target);
4025 if (e != ERROR_OK) {
4026 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4033 if (goi.argc != 2) {
4034 Jim_WrongNumArgs(interp, 2, argv,
4035 "([tT]|[fF]|assert|deassert) BOOL");
4038 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4040 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4043 /* the halt or not param */
4044 e = Jim_GetOpt_Wide(&goi, &a);
4048 if (!target->tap->enabled)
4049 goto err_tap_disabled;
4050 if (!target->type->assert_reset
4051 || !target->type->deassert_reset) {
4052 Jim_SetResult_sprintf(interp,
4053 "No target-specific reset for %s",
4057 /* determine if we should halt or not. */
4058 target->reset_halt = !!a;
4059 /* When this happens - all workareas are invalid. */
4060 target_free_all_working_areas_restore(target, 0);
4063 if (n->value == NVP_ASSERT) {
4064 target->type->assert_reset(target);
4066 target->type->deassert_reset(target);
4071 Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4074 if (!target->tap->enabled)
4075 goto err_tap_disabled;
4076 target->type->halt(target);
4078 case TS_CMD_WAITSTATE:
4079 /* params: <name> statename timeoutmsecs */
4080 if (goi.argc != 2) {
4081 Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4084 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4086 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4089 e = Jim_GetOpt_Wide(&goi, &a);
4093 if (!target->tap->enabled)
4094 goto err_tap_disabled;
4095 e = target_wait_state(target, n->value, a);
4096 if (e != ERROR_OK) {
4097 Jim_SetResult_sprintf(goi.interp,
4098 "target: %s wait %s fails (%d) %s",
4101 e, target_strerror_safe(e));
4106 case TS_CMD_EVENTLIST:
4107 /* List for human, Events defined for this target.
4108 * scripts/programs should use 'name cget -event NAME'
4111 target_event_action_t *teap;
4112 teap = target->event_action;
4113 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4114 target->target_number,
4116 command_print(cmd_ctx, "%-25s | Body", "Event");
4117 command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4119 command_print(cmd_ctx,
4121 Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4122 Jim_GetString(teap->body, NULL));
4125 command_print(cmd_ctx, "***END***");
4128 case TS_CMD_CURSTATE:
4129 if (goi.argc != 0) {
4130 Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4133 Jim_SetResultString(goi.interp,
4134 target_state_name( target ),
4137 case TS_CMD_INVOKE_EVENT:
4138 if (goi.argc != 1) {
4139 Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4142 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4144 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4147 target_handle_event(target, n->value);
4153 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4157 static int target_create(Jim_GetOptInfo *goi)
4166 struct command_context_s *cmd_ctx;
4168 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4169 if (goi->argc < 3) {
4170 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4175 Jim_GetOpt_Obj(goi, &new_cmd);
4176 /* does this command exist? */
4177 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4179 cp = Jim_GetString(new_cmd, NULL);
4180 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4185 e = Jim_GetOpt_String(goi, &cp2, NULL);
4187 /* now does target type exist */
4188 for (x = 0 ; target_types[x] ; x++) {
4189 if (0 == strcmp(cp, target_types[x]->name)) {
4194 if (target_types[x] == NULL) {
4195 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4196 for (x = 0 ; target_types[x] ; x++) {
4197 if (target_types[x + 1]) {
4198 Jim_AppendStrings(goi->interp,
4199 Jim_GetResult(goi->interp),
4200 target_types[x]->name,
4203 Jim_AppendStrings(goi->interp,
4204 Jim_GetResult(goi->interp),
4206 target_types[x]->name,NULL);
4213 target = calloc(1,sizeof(target_t));
4214 /* set target number */
4215 target->target_number = new_target_number();
4217 /* allocate memory for each unique target type */
4218 target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4220 memcpy(target->type, target_types[x], sizeof(target_type_t));
4222 /* will be set by "-endian" */
4223 target->endianness = TARGET_ENDIAN_UNKNOWN;
4225 target->working_area = 0x0;
4226 target->working_area_size = 0x0;
4227 target->working_areas = NULL;
4228 target->backup_working_area = 0;
4230 target->state = TARGET_UNKNOWN;
4231 target->debug_reason = DBG_REASON_UNDEFINED;
4232 target->reg_cache = NULL;
4233 target->breakpoints = NULL;
4234 target->watchpoints = NULL;
4235 target->next = NULL;
4236 target->arch_info = NULL;
4238 target->display = 1;
4240 /* initialize trace information */
4241 target->trace_info = malloc(sizeof(trace_t));
4242 target->trace_info->num_trace_points = 0;
4243 target->trace_info->trace_points_size = 0;
4244 target->trace_info->trace_points = NULL;
4245 target->trace_info->trace_history_size = 0;
4246 target->trace_info->trace_history = NULL;
4247 target->trace_info->trace_history_pos = 0;
4248 target->trace_info->trace_history_overflowed = 0;
4250 target->dbgmsg = NULL;
4251 target->dbg_msg_enabled = 0;
4253 target->endianness = TARGET_ENDIAN_UNKNOWN;
4255 /* Do the rest as "configure" options */
4256 goi->isconfigure = 1;
4257 e = target_configure(goi, target);
4259 if (target->tap == NULL)
4261 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4271 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4272 /* default endian to little if not specified */
4273 target->endianness = TARGET_LITTLE_ENDIAN;
4276 /* incase variant is not set */
4277 if (!target->variant)
4278 target->variant = strdup("");
4280 /* create the target specific commands */
4281 if (target->type->register_commands) {
4282 (*(target->type->register_commands))(cmd_ctx);
4284 if (target->type->target_create) {
4285 (*(target->type->target_create))(target, goi->interp);
4288 /* append to end of list */
4291 tpp = &(all_targets);
4293 tpp = &((*tpp)->next);
4298 cp = Jim_GetString(new_cmd, NULL);
4299 target->cmd_name = strdup(cp);
4301 /* now - create the new target name command */
4302 e = Jim_CreateCommand(goi->interp,
4305 tcl_target_func, /* C function */
4306 target, /* private data */
4307 NULL); /* no del proc */
4312 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4316 struct command_context_s *cmd_ctx;
4320 /* TG = target generic */
4328 const char *target_cmds[] = {
4329 "create", "types", "names", "current", "number",
4331 NULL /* terminate */
4334 LOG_DEBUG("Target command params:");
4335 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4337 cmd_ctx = Jim_GetAssocData(interp, "context");
4339 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4341 if (goi.argc == 0) {
4342 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4346 /* Jim_GetOpt_Debug(&goi); */
4347 r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4354 Jim_Panic(goi.interp,"Why am I here?");
4356 case TG_CMD_CURRENT:
4357 if (goi.argc != 0) {
4358 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4361 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4364 if (goi.argc != 0) {
4365 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4368 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4369 for (x = 0 ; target_types[x] ; x++) {
4370 Jim_ListAppendElement(goi.interp,
4371 Jim_GetResult(goi.interp),
4372 Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4376 if (goi.argc != 0) {
4377 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4380 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4381 target = all_targets;
4383 Jim_ListAppendElement(goi.interp,
4384 Jim_GetResult(goi.interp),
4385 Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4386 target = target->next;
4391 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4394 return target_create(&goi);
4397 /* It's OK to remove this mechanism sometime after August 2010 or so */
4398 LOG_WARNING("don't use numbers as target identifiers; use names");
4399 if (goi.argc != 1) {
4400 Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4403 e = Jim_GetOpt_Wide(&goi, &w);
4407 for (x = 0, target = all_targets; target; target = target->next, x++) {
4408 if (target->target_number == w)
4411 if (target == NULL) {
4412 Jim_SetResult_sprintf(goi.interp,
4413 "Target: number %d does not exist", (int)(w));
4416 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4419 if (goi.argc != 0) {
4420 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4423 for (x = 0, target = all_targets; target; target = target->next, x++)
4425 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4441 static int fastload_num;
4442 static struct FastLoad *fastload;
4444 static void free_fastload(void)
4446 if (fastload != NULL)
4449 for (i = 0; i < fastload_num; i++)
4451 if (fastload[i].data)
4452 free(fastload[i].data);
4462 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4466 uint32_t image_size;
4467 uint32_t min_address = 0;
4468 uint32_t max_address = 0xffffffff;
4473 duration_t duration;
4474 char *duration_text;
4476 int retval = parse_load_image_command_args(args, argc,
4477 &image, &min_address, &max_address);
4478 if (ERROR_OK != retval)
4481 duration_start_measure(&duration);
4483 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4490 fastload_num = image.num_sections;
4491 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4492 if (fastload == NULL)
4494 image_close(&image);
4497 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4498 for (i = 0; i < image.num_sections; i++)
4500 buffer = malloc(image.sections[i].size);
4503 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4504 (int)(image.sections[i].size));
4508 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4514 uint32_t offset = 0;
4515 uint32_t length = buf_cnt;
4518 /* DANGER!!! beware of unsigned comparision here!!! */
4520 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4521 (image.sections[i].base_address < max_address))
4523 if (image.sections[i].base_address < min_address)
4525 /* clip addresses below */
4526 offset += min_address-image.sections[i].base_address;
4530 if (image.sections[i].base_address + buf_cnt > max_address)
4532 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4535 fastload[i].address = image.sections[i].base_address + offset;
4536 fastload[i].data = malloc(length);
4537 if (fastload[i].data == NULL)
4542 memcpy(fastload[i].data, buffer + offset, length);
4543 fastload[i].length = length;
4545 image_size += length;
4546 command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4547 (unsigned int)length,
4548 ((unsigned int)(image.sections[i].base_address + offset)));
4554 duration_stop_measure(&duration, &duration_text);
4555 if (retval == ERROR_OK)
4557 command_print(cmd_ctx, "Loaded %u bytes in %s", (unsigned int)image_size, duration_text);
4558 command_print(cmd_ctx, "NB!!! image has not been loaded to target, issue a subsequent 'fast_load' to do so.");
4560 free(duration_text);
4562 image_close(&image);
4564 if (retval != ERROR_OK)
4572 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4575 return ERROR_COMMAND_SYNTAX_ERROR;
4576 if (fastload == NULL)
4578 LOG_ERROR("No image in memory");
4582 int ms = timeval_ms();
4584 int retval = ERROR_OK;
4585 for (i = 0; i < fastload_num;i++)
4587 target_t *target = get_current_target(cmd_ctx);
4588 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4589 (unsigned int)(fastload[i].address),
4590 (unsigned int)(fastload[i].length));
4591 if (retval == ERROR_OK)
4593 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4595 size += fastload[i].length;
4597 int after = timeval_ms();
4598 command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));