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 /* read a uint32_t from a buffer in target memory endianness */
273 uint32_t target_buffer_get_u32(target_t *target, const uint8_t *buffer)
275 if (target->endianness == TARGET_LITTLE_ENDIAN)
276 return le_to_h_u32(buffer);
278 return be_to_h_u32(buffer);
281 /* read a uint16_t from a buffer in target memory endianness */
282 uint16_t target_buffer_get_u16(target_t *target, const uint8_t *buffer)
284 if (target->endianness == TARGET_LITTLE_ENDIAN)
285 return le_to_h_u16(buffer);
287 return be_to_h_u16(buffer);
290 /* read a uint8_t from a buffer in target memory endianness */
291 uint8_t target_buffer_get_u8(target_t *target, const uint8_t *buffer)
293 return *buffer & 0x0ff;
296 /* write a uint32_t to a buffer in target memory endianness */
297 void target_buffer_set_u32(target_t *target, uint8_t *buffer, uint32_t value)
299 if (target->endianness == TARGET_LITTLE_ENDIAN)
300 h_u32_to_le(buffer, value);
302 h_u32_to_be(buffer, value);
305 /* write a uint16_t to a buffer in target memory endianness */
306 void target_buffer_set_u16(target_t *target, uint8_t *buffer, uint16_t value)
308 if (target->endianness == TARGET_LITTLE_ENDIAN)
309 h_u16_to_le(buffer, value);
311 h_u16_to_be(buffer, value);
314 /* write a uint8_t to a buffer in target memory endianness */
315 void target_buffer_set_u8(target_t *target, uint8_t *buffer, uint8_t value)
320 /* return a pointer to a configured target; id is name or number */
321 target_t *get_target(const char *id)
325 /* try as tcltarget name */
326 for (target = all_targets; target; target = target->next) {
327 if (target->cmd_name == NULL)
329 if (strcmp(id, target->cmd_name) == 0)
333 /* It's OK to remove this fallback sometime after August 2010 or so */
335 /* no match, try as number */
337 if (parse_uint(id, &num) != ERROR_OK)
340 for (target = all_targets; target; target = target->next) {
341 if (target->target_number == (int)num) {
342 LOG_WARNING("use '%s' as target identifier, not '%u'",
343 target->cmd_name, num);
351 /* returns a pointer to the n-th configured target */
352 static target_t *get_target_by_num(int num)
354 target_t *target = all_targets;
357 if (target->target_number == num) {
360 target = target->next;
366 target_t* get_current_target(command_context_t *cmd_ctx)
368 target_t *target = get_target_by_num(cmd_ctx->current_target);
372 LOG_ERROR("BUG: current_target out of bounds");
379 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 */
390 retval = target->type->poll(target);
391 if (retval != ERROR_OK)
394 if (target->halt_issued)
396 if (target->state == TARGET_HALTED)
398 target->halt_issued = false;
401 long long t = timeval_ms() - target->halt_issued_time;
404 target->halt_issued = false;
405 LOG_INFO("Halt timed out, wake up GDB.");
406 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
414 int target_halt(struct target_s *target)
417 /* We can't poll until after examine */
418 if (!target_was_examined(target))
420 LOG_ERROR("Target not examined yet");
424 retval = target->type->halt(target);
425 if (retval != ERROR_OK)
428 target->halt_issued = true;
429 target->halt_issued_time = timeval_ms();
434 int target_resume(struct target_s *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
438 /* We can't poll until after examine */
439 if (!target_was_examined(target))
441 LOG_ERROR("Target not examined yet");
445 /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
446 * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
449 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
455 int target_process_reset(struct command_context_s *cmd_ctx, enum target_reset_mode reset_mode)
460 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
461 if (n->name == NULL) {
462 LOG_ERROR("invalid reset mode");
466 /* disable polling during reset to make reset event scripts
467 * more predictable, i.e. dr/irscan & pathmove in events will
468 * not have JTAG operations injected into the middle of a sequence.
470 bool save_poll = jtag_poll_get_enabled();
472 jtag_poll_set_enabled(false);
474 sprintf(buf, "ocd_process_reset %s", n->name);
475 retval = Jim_Eval(interp, buf);
477 jtag_poll_set_enabled(save_poll);
479 if (retval != JIM_OK) {
480 Jim_PrintErrorMessage(interp);
484 /* We want any events to be processed before the prompt */
485 retval = target_call_timer_callbacks_now();
490 static int default_virt2phys(struct target_s *target, uint32_t virtual, uint32_t *physical)
496 static int default_mmu(struct target_s *target, int *enabled)
502 static int default_examine(struct target_s *target)
504 target_set_examined(target);
508 int target_examine_one(struct target_s *target)
510 return target->type->examine(target);
513 static int jtag_enable_callback(enum jtag_event event, void *priv)
515 target_t *target = priv;
517 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
520 jtag_unregister_event_callback(jtag_enable_callback, target);
521 return target_examine_one(target);
525 /* Targets that correctly implement init + examine, i.e.
526 * no communication with target during init:
530 int target_examine(void)
532 int retval = ERROR_OK;
535 for (target = all_targets; target; target = target->next)
537 /* defer examination, but don't skip it */
538 if (!target->tap->enabled) {
539 jtag_register_event_callback(jtag_enable_callback,
543 if ((retval = target_examine_one(target)) != ERROR_OK)
548 const char *target_get_name(struct target_s *target)
550 return target->type->name;
553 static int target_write_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
555 if (!target_was_examined(target))
557 LOG_ERROR("Target not examined yet");
560 return target->type->write_memory_imp(target, address, size, count, buffer);
563 static int target_read_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
565 if (!target_was_examined(target))
567 LOG_ERROR("Target not examined yet");
570 return target->type->read_memory_imp(target, address, size, count, buffer);
573 static int target_soft_reset_halt_imp(struct target_s *target)
575 if (!target_was_examined(target))
577 LOG_ERROR("Target not examined yet");
580 if (!target->type->soft_reset_halt_imp) {
581 LOG_ERROR("Target %s does not support soft_reset_halt",
585 return target->type->soft_reset_halt_imp(target);
588 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)
590 if (!target_was_examined(target))
592 LOG_ERROR("Target not examined yet");
595 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);
598 int target_read_memory(struct target_s *target,
599 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
601 return target->type->read_memory(target, address, size, count, buffer);
604 int target_write_memory(struct target_s *target,
605 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
607 return target->type->write_memory(target, address, size, count, buffer);
609 int target_bulk_write_memory(struct target_s *target,
610 uint32_t address, uint32_t count, uint8_t *buffer)
612 return target->type->bulk_write_memory(target, address, count, buffer);
615 int target_add_breakpoint(struct target_s *target,
616 struct breakpoint_s *breakpoint)
618 return target->type->add_breakpoint(target, breakpoint);
620 int target_remove_breakpoint(struct target_s *target,
621 struct breakpoint_s *breakpoint)
623 return target->type->remove_breakpoint(target, breakpoint);
626 int target_add_watchpoint(struct target_s *target,
627 struct watchpoint_s *watchpoint)
629 return target->type->add_watchpoint(target, watchpoint);
631 int target_remove_watchpoint(struct target_s *target,
632 struct watchpoint_s *watchpoint)
634 return target->type->remove_watchpoint(target, watchpoint);
637 int target_get_gdb_reg_list(struct target_s *target,
638 struct reg_s **reg_list[], int *reg_list_size)
640 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
642 int target_step(struct target_s *target,
643 int current, uint32_t address, int handle_breakpoints)
645 return target->type->step(target, current, address, handle_breakpoints);
649 int target_run_algorithm(struct target_s *target,
650 int num_mem_params, mem_param_t *mem_params,
651 int num_reg_params, reg_param_t *reg_param,
652 uint32_t entry_point, uint32_t exit_point,
653 int timeout_ms, void *arch_info)
655 return target->type->run_algorithm(target,
656 num_mem_params, mem_params, num_reg_params, reg_param,
657 entry_point, exit_point, timeout_ms, arch_info);
660 /// @returns @c true if the target has been examined.
661 bool target_was_examined(struct target_s *target)
663 return target->type->examined;
665 /// Sets the @c examined flag for the given target.
666 void target_set_examined(struct target_s *target)
668 target->type->examined = true;
670 // Reset the @c examined flag for the given target.
671 void target_reset_examined(struct target_s *target)
673 target->type->examined = false;
677 int target_init(struct command_context_s *cmd_ctx)
679 target_t *target = all_targets;
684 target_reset_examined(target);
685 if (target->type->examine == NULL)
687 target->type->examine = default_examine;
690 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
692 LOG_ERROR("target '%s' init failed", target_get_name(target));
696 /* Set up default functions if none are provided by target */
697 if (target->type->virt2phys == NULL)
699 target->type->virt2phys = default_virt2phys;
701 /* a non-invasive way(in terms of patches) to add some code that
702 * runs before the type->write/read_memory implementation
704 target->type->write_memory_imp = target->type->write_memory;
705 target->type->write_memory = target_write_memory_imp;
706 target->type->read_memory_imp = target->type->read_memory;
707 target->type->read_memory = target_read_memory_imp;
708 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
709 target->type->soft_reset_halt = target_soft_reset_halt_imp;
710 target->type->run_algorithm_imp = target->type->run_algorithm;
711 target->type->run_algorithm = target_run_algorithm_imp;
713 if (target->type->mmu == NULL)
715 target->type->mmu = default_mmu;
717 target = target->next;
722 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
724 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
731 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
733 target_event_callback_t **callbacks_p = &target_event_callbacks;
735 if (callback == NULL)
737 return ERROR_INVALID_ARGUMENTS;
742 while ((*callbacks_p)->next)
743 callbacks_p = &((*callbacks_p)->next);
744 callbacks_p = &((*callbacks_p)->next);
747 (*callbacks_p) = malloc(sizeof(target_event_callback_t));
748 (*callbacks_p)->callback = callback;
749 (*callbacks_p)->priv = priv;
750 (*callbacks_p)->next = NULL;
755 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
757 target_timer_callback_t **callbacks_p = &target_timer_callbacks;
760 if (callback == NULL)
762 return ERROR_INVALID_ARGUMENTS;
767 while ((*callbacks_p)->next)
768 callbacks_p = &((*callbacks_p)->next);
769 callbacks_p = &((*callbacks_p)->next);
772 (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
773 (*callbacks_p)->callback = callback;
774 (*callbacks_p)->periodic = periodic;
775 (*callbacks_p)->time_ms = time_ms;
777 gettimeofday(&now, NULL);
778 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
779 time_ms -= (time_ms % 1000);
780 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
781 if ((*callbacks_p)->when.tv_usec > 1000000)
783 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
784 (*callbacks_p)->when.tv_sec += 1;
787 (*callbacks_p)->priv = priv;
788 (*callbacks_p)->next = NULL;
793 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
795 target_event_callback_t **p = &target_event_callbacks;
796 target_event_callback_t *c = target_event_callbacks;
798 if (callback == NULL)
800 return ERROR_INVALID_ARGUMENTS;
805 target_event_callback_t *next = c->next;
806 if ((c->callback == callback) && (c->priv == priv))
820 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
822 target_timer_callback_t **p = &target_timer_callbacks;
823 target_timer_callback_t *c = target_timer_callbacks;
825 if (callback == NULL)
827 return ERROR_INVALID_ARGUMENTS;
832 target_timer_callback_t *next = c->next;
833 if ((c->callback == callback) && (c->priv == priv))
847 int target_call_event_callbacks(target_t *target, enum target_event event)
849 target_event_callback_t *callback = target_event_callbacks;
850 target_event_callback_t *next_callback;
852 if (event == TARGET_EVENT_HALTED)
854 /* execute early halted first */
855 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
858 LOG_DEBUG("target event %i (%s)",
860 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
862 target_handle_event(target, event);
866 next_callback = callback->next;
867 callback->callback(target, event, callback->priv);
868 callback = next_callback;
874 static int target_timer_callback_periodic_restart(
875 target_timer_callback_t *cb, struct timeval *now)
877 int time_ms = cb->time_ms;
878 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
879 time_ms -= (time_ms % 1000);
880 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
881 if (cb->when.tv_usec > 1000000)
883 cb->when.tv_usec = cb->when.tv_usec - 1000000;
884 cb->when.tv_sec += 1;
889 static int target_call_timer_callback(target_timer_callback_t *cb,
892 cb->callback(cb->priv);
895 return target_timer_callback_periodic_restart(cb, now);
897 return target_unregister_timer_callback(cb->callback, cb->priv);
900 static int target_call_timer_callbacks_check_time(int checktime)
905 gettimeofday(&now, NULL);
907 target_timer_callback_t *callback = target_timer_callbacks;
910 // cleaning up may unregister and free this callback
911 target_timer_callback_t *next_callback = callback->next;
913 bool call_it = callback->callback &&
914 ((!checktime && callback->periodic) ||
915 now.tv_sec > callback->when.tv_sec ||
916 (now.tv_sec == callback->when.tv_sec &&
917 now.tv_usec >= callback->when.tv_usec));
921 int retval = target_call_timer_callback(callback, &now);
922 if (retval != ERROR_OK)
926 callback = next_callback;
932 int target_call_timer_callbacks(void)
934 return target_call_timer_callbacks_check_time(1);
937 /* invoke periodic callbacks immediately */
938 int target_call_timer_callbacks_now(void)
940 return target_call_timer_callbacks_check_time(0);
943 int target_alloc_working_area(struct target_s *target, uint32_t size, working_area_t **area)
945 working_area_t *c = target->working_areas;
946 working_area_t *new_wa = NULL;
948 /* Reevaluate working area address based on MMU state*/
949 if (target->working_areas == NULL)
953 retval = target->type->mmu(target, &enabled);
954 if (retval != ERROR_OK)
960 target->working_area = target->working_area_virt;
964 target->working_area = target->working_area_phys;
968 /* only allocate multiples of 4 byte */
971 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
972 size = (size + 3) & (~3);
975 /* see if there's already a matching working area */
978 if ((c->free) && (c->size == size))
986 /* if not, allocate a new one */
989 working_area_t **p = &target->working_areas;
990 uint32_t first_free = target->working_area;
991 uint32_t free_size = target->working_area_size;
993 LOG_DEBUG("allocating new working area");
995 c = target->working_areas;
998 first_free += c->size;
999 free_size -= c->size;
1004 if (free_size < size)
1006 LOG_WARNING("not enough working area available(requested %u, free %u)",
1007 (unsigned)(size), (unsigned)(free_size));
1008 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1011 new_wa = malloc(sizeof(working_area_t));
1012 new_wa->next = NULL;
1013 new_wa->size = size;
1014 new_wa->address = first_free;
1016 if (target->backup_working_area)
1019 new_wa->backup = malloc(new_wa->size);
1020 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1022 free(new_wa->backup);
1029 new_wa->backup = NULL;
1032 /* put new entry in list */
1036 /* mark as used, and return the new (reused) area */
1041 new_wa->user = area;
1046 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
1051 if (restore && target->backup_working_area)
1054 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1060 /* mark user pointer invalid */
1067 int target_free_working_area(struct target_s *target, working_area_t *area)
1069 return target_free_working_area_restore(target, area, 1);
1072 /* free resources and restore memory, if restoring memory fails,
1073 * free up resources anyway
1075 void target_free_all_working_areas_restore(struct target_s *target, int restore)
1077 working_area_t *c = target->working_areas;
1081 working_area_t *next = c->next;
1082 target_free_working_area_restore(target, c, restore);
1092 target->working_areas = NULL;
1095 void target_free_all_working_areas(struct target_s *target)
1097 target_free_all_working_areas_restore(target, 1);
1100 int target_register_commands(struct command_context_s *cmd_ctx)
1103 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)");
1108 register_jim(cmd_ctx, "target", jim_target, "configure target");
1113 int target_arch_state(struct target_s *target)
1118 LOG_USER("No target has been configured");
1122 LOG_USER("target state: %s", target_state_name( target ));
1124 if (target->state != TARGET_HALTED)
1127 retval = target->type->arch_state(target);
1131 /* Single aligned words are guaranteed to use 16 or 32 bit access
1132 * mode respectively, otherwise data is handled as quickly as
1135 int target_write_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1138 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1139 (int)size, (unsigned)address);
1141 if (!target_was_examined(target))
1143 LOG_ERROR("Target not examined yet");
1151 if ((address + size - 1) < address)
1153 /* GDB can request this when e.g. PC is 0xfffffffc*/
1154 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1160 if (((address % 2) == 0) && (size == 2))
1162 return target_write_memory(target, address, 2, 1, buffer);
1165 /* handle unaligned head bytes */
1168 uint32_t unaligned = 4 - (address % 4);
1170 if (unaligned > size)
1173 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1176 buffer += unaligned;
1177 address += unaligned;
1181 /* handle aligned words */
1184 int aligned = size - (size % 4);
1186 /* use bulk writes above a certain limit. This may have to be changed */
1189 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1194 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1203 /* handle tail writes of less than 4 bytes */
1206 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1213 /* Single aligned words are guaranteed to use 16 or 32 bit access
1214 * mode respectively, otherwise data is handled as quickly as
1217 int target_read_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1220 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1221 (int)size, (unsigned)address);
1223 if (!target_was_examined(target))
1225 LOG_ERROR("Target not examined yet");
1233 if ((address + size - 1) < address)
1235 /* GDB can request this when e.g. PC is 0xfffffffc*/
1236 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1242 if (((address % 2) == 0) && (size == 2))
1244 return target_read_memory(target, address, 2, 1, buffer);
1247 /* handle unaligned head bytes */
1250 uint32_t unaligned = 4 - (address % 4);
1252 if (unaligned > size)
1255 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1258 buffer += unaligned;
1259 address += unaligned;
1263 /* handle aligned words */
1266 int aligned = size - (size % 4);
1268 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1276 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1279 int aligned = size - (size%2);
1280 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1281 if (retval != ERROR_OK)
1288 /* handle tail writes of less than 4 bytes */
1291 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1298 int target_checksum_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* crc)
1303 uint32_t checksum = 0;
1304 if (!target_was_examined(target))
1306 LOG_ERROR("Target not examined yet");
1310 if ((retval = target->type->checksum_memory(target, address,
1311 size, &checksum)) != ERROR_OK)
1313 buffer = malloc(size);
1316 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1317 return ERROR_INVALID_ARGUMENTS;
1319 retval = target_read_buffer(target, address, size, buffer);
1320 if (retval != ERROR_OK)
1326 /* convert to target endianess */
1327 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1329 uint32_t target_data;
1330 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1331 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1334 retval = image_calculate_checksum(buffer, size, &checksum);
1343 int target_blank_check_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* blank)
1346 if (!target_was_examined(target))
1348 LOG_ERROR("Target not examined yet");
1352 if (target->type->blank_check_memory == 0)
1353 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1355 retval = target->type->blank_check_memory(target, address, size, blank);
1360 int target_read_u32(struct target_s *target, uint32_t address, uint32_t *value)
1362 uint8_t value_buf[4];
1363 if (!target_was_examined(target))
1365 LOG_ERROR("Target not examined yet");
1369 int retval = target_read_memory(target, address, 4, 1, value_buf);
1371 if (retval == ERROR_OK)
1373 *value = target_buffer_get_u32(target, value_buf);
1374 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1381 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1388 int target_read_u16(struct target_s *target, uint32_t address, uint16_t *value)
1390 uint8_t value_buf[2];
1391 if (!target_was_examined(target))
1393 LOG_ERROR("Target not examined yet");
1397 int retval = target_read_memory(target, address, 2, 1, value_buf);
1399 if (retval == ERROR_OK)
1401 *value = target_buffer_get_u16(target, value_buf);
1402 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1409 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1416 int target_read_u8(struct target_s *target, uint32_t address, uint8_t *value)
1418 int retval = target_read_memory(target, address, 1, 1, value);
1419 if (!target_was_examined(target))
1421 LOG_ERROR("Target not examined yet");
1425 if (retval == ERROR_OK)
1427 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1434 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1441 int target_write_u32(struct target_s *target, uint32_t address, uint32_t value)
1444 uint8_t value_buf[4];
1445 if (!target_was_examined(target))
1447 LOG_ERROR("Target not examined yet");
1451 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1455 target_buffer_set_u32(target, value_buf, value);
1456 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1458 LOG_DEBUG("failed: %i", retval);
1464 int target_write_u16(struct target_s *target, uint32_t address, uint16_t value)
1467 uint8_t value_buf[2];
1468 if (!target_was_examined(target))
1470 LOG_ERROR("Target not examined yet");
1474 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1478 target_buffer_set_u16(target, value_buf, value);
1479 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1481 LOG_DEBUG("failed: %i", retval);
1487 int target_write_u8(struct target_s *target, uint32_t address, uint8_t value)
1490 if (!target_was_examined(target))
1492 LOG_ERROR("Target not examined yet");
1496 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1499 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1501 LOG_DEBUG("failed: %i", retval);
1507 int target_register_user_commands(struct command_context_s *cmd_ctx)
1509 int retval = ERROR_OK;
1512 /* script procedures */
1513 register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "profiling samples the CPU PC");
1514 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>");
1515 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>");
1517 register_command(cmd_ctx, NULL, "fast_load_image", handle_fast_load_image_command, COMMAND_ANY,
1518 "same args as load_image, image stored in memory - mainly for profiling purposes");
1520 register_command(cmd_ctx, NULL, "fast_load", handle_fast_load_command, COMMAND_ANY,
1521 "loads active fast load image to current target - mainly for profiling purposes");
1524 register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "translate a virtual address into a physical address");
1525 register_command(cmd_ctx, NULL, "reg", handle_reg_command, COMMAND_EXEC, "display or set a register");
1526 register_command(cmd_ctx, NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1527 register_command(cmd_ctx, NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1528 register_command(cmd_ctx, NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1529 register_command(cmd_ctx, NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1530 register_command(cmd_ctx, NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1531 register_command(cmd_ctx, NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run | halt | init] - default is run");
1532 register_command(cmd_ctx, NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1534 register_command(cmd_ctx, NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words <addr> [count]");
1535 register_command(cmd_ctx, NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words <addr> [count]");
1536 register_command(cmd_ctx, NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes <addr> [count]");
1538 register_command(cmd_ctx, NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word <addr> <value> [count]");
1539 register_command(cmd_ctx, NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word <addr> <value> [count]");
1540 register_command(cmd_ctx, NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte <addr> <value> [count]");
1542 register_command(cmd_ctx, NULL, "bp",
1543 handle_bp_command, COMMAND_EXEC,
1544 "list or set breakpoint [<address> <length> [hw]]");
1545 register_command(cmd_ctx, NULL, "rbp",
1546 handle_rbp_command, COMMAND_EXEC,
1547 "remove breakpoint <address>");
1548 register_command(cmd_ctx, NULL, "wp",
1549 handle_wp_command, COMMAND_EXEC,
1550 "list or set watchpoint "
1551 "[<address> <length> <r/w/a> [value] [mask]]");
1552 register_command(cmd_ctx, NULL, "rwp",
1553 handle_rwp_command, COMMAND_EXEC,
1554 "remove watchpoint <address>");
1556 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]");
1557 register_command(cmd_ctx, NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1558 register_command(cmd_ctx, NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1559 register_command(cmd_ctx, NULL, "test_image", handle_test_image_command, COMMAND_EXEC, "test_image <file> [offset] [type]");
1561 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
1563 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
1569 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1571 target_t *target = all_targets;
1575 target = get_target(args[0]);
1576 if (target == NULL) {
1577 command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1580 if (!target->tap->enabled) {
1581 command_print(cmd_ctx,"Target: TAP %s is disabled, "
1582 "can't be the current target\n",
1583 target->tap->dotted_name);
1587 cmd_ctx->current_target = target->target_number;
1592 target = all_targets;
1593 command_print(cmd_ctx, " TargetName Type Endian TapName State ");
1594 command_print(cmd_ctx, "-- ------------------ ---------- ------ ------------------ ------------");
1600 if (target->tap->enabled)
1601 state = target_state_name( target );
1603 state = "tap-disabled";
1605 if (cmd_ctx->current_target == target->target_number)
1608 /* keep columns lined up to match the headers above */
1609 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1610 target->target_number,
1613 target_get_name(target),
1614 Jim_Nvp_value2name_simple(nvp_target_endian,
1615 target->endianness)->name,
1616 target->tap->dotted_name,
1618 target = target->next;
1624 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1626 static int powerDropout;
1627 static int srstAsserted;
1629 static int runPowerRestore;
1630 static int runPowerDropout;
1631 static int runSrstAsserted;
1632 static int runSrstDeasserted;
1634 static int sense_handler(void)
1636 static int prevSrstAsserted = 0;
1637 static int prevPowerdropout = 0;
1640 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1644 powerRestored = prevPowerdropout && !powerDropout;
1647 runPowerRestore = 1;
1650 long long current = timeval_ms();
1651 static long long lastPower = 0;
1652 int waitMore = lastPower + 2000 > current;
1653 if (powerDropout && !waitMore)
1655 runPowerDropout = 1;
1656 lastPower = current;
1659 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1663 srstDeasserted = prevSrstAsserted && !srstAsserted;
1665 static long long lastSrst = 0;
1666 waitMore = lastSrst + 2000 > current;
1667 if (srstDeasserted && !waitMore)
1669 runSrstDeasserted = 1;
1673 if (!prevSrstAsserted && srstAsserted)
1675 runSrstAsserted = 1;
1678 prevSrstAsserted = srstAsserted;
1679 prevPowerdropout = powerDropout;
1681 if (srstDeasserted || powerRestored)
1683 /* Other than logging the event we can't do anything here.
1684 * Issuing a reset is a particularly bad idea as we might
1685 * be inside a reset already.
1692 static void target_call_event_callbacks_all(enum target_event e) {
1694 target = all_targets;
1696 target_call_event_callbacks(target, e);
1697 target = target->next;
1701 /* process target state changes */
1702 int handle_target(void *priv)
1704 int retval = ERROR_OK;
1706 /* we do not want to recurse here... */
1707 static int recursive = 0;
1712 /* danger! running these procedures can trigger srst assertions and power dropouts.
1713 * We need to avoid an infinite loop/recursion here and we do that by
1714 * clearing the flags after running these events.
1716 int did_something = 0;
1717 if (runSrstAsserted)
1719 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1720 Jim_Eval(interp, "srst_asserted");
1723 if (runSrstDeasserted)
1725 Jim_Eval(interp, "srst_deasserted");
1728 if (runPowerDropout)
1730 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1731 Jim_Eval(interp, "power_dropout");
1734 if (runPowerRestore)
1736 Jim_Eval(interp, "power_restore");
1742 /* clear detect flags */
1746 /* clear action flags */
1748 runSrstAsserted = 0;
1749 runSrstDeasserted = 0;
1750 runPowerRestore = 0;
1751 runPowerDropout = 0;
1756 /* Poll targets for state changes unless that's globally disabled.
1757 * Skip targets that are currently disabled.
1759 for (target_t *target = all_targets;
1760 is_jtag_poll_safe() && target;
1761 target = target->next)
1763 if (!target->tap->enabled)
1766 /* only poll target if we've got power and srst isn't asserted */
1767 if (!powerDropout && !srstAsserted)
1769 /* polling may fail silently until the target has been examined */
1770 if ((retval = target_poll(target)) != ERROR_OK)
1772 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1781 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1790 target = get_current_target(cmd_ctx);
1792 /* list all available registers for the current target */
1795 reg_cache_t *cache = target->reg_cache;
1802 for (i = 0, reg = cache->reg_list;
1803 i < cache->num_regs;
1804 i++, reg++, count++)
1806 /* only print cached values if they are valid */
1808 value = buf_to_str(reg->value,
1810 command_print(cmd_ctx,
1811 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1819 command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1824 cache = cache->next;
1830 /* access a single register by its ordinal number */
1831 if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1834 int retval = parse_uint(args[0], &num);
1835 if (ERROR_OK != retval)
1836 return ERROR_COMMAND_SYNTAX_ERROR;
1838 reg_cache_t *cache = target->reg_cache;
1843 for (i = 0; i < cache->num_regs; i++)
1845 if (count++ == (int)num)
1847 reg = &cache->reg_list[i];
1853 cache = cache->next;
1858 command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1861 } else /* access a single register by its name */
1863 reg = register_get_by_name(target->reg_cache, args[0], 1);
1867 command_print(cmd_ctx, "register %s not found in current target", args[0]);
1872 /* display a register */
1873 if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1875 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1878 if (reg->valid == 0)
1880 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1881 arch_type->get(reg);
1883 value = buf_to_str(reg->value, reg->size, 16);
1884 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1889 /* set register value */
1892 uint8_t *buf = malloc(CEIL(reg->size, 8));
1893 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1895 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1896 arch_type->set(reg, buf);
1898 value = buf_to_str(reg->value, reg->size, 16);
1899 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1907 command_print(cmd_ctx, "usage: reg <#|name> [value]");
1912 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1914 int retval = ERROR_OK;
1915 target_t *target = get_current_target(cmd_ctx);
1919 command_print(cmd_ctx, "background polling: %s",
1920 jtag_poll_get_enabled() ? "on" : "off");
1921 command_print(cmd_ctx, "TAP: %s (%s)",
1922 target->tap->dotted_name,
1923 target->tap->enabled ? "enabled" : "disabled");
1924 if (!target->tap->enabled)
1926 if ((retval = target_poll(target)) != ERROR_OK)
1928 if ((retval = target_arch_state(target)) != ERROR_OK)
1934 if (strcmp(args[0], "on") == 0)
1936 jtag_poll_set_enabled(true);
1938 else if (strcmp(args[0], "off") == 0)
1940 jtag_poll_set_enabled(false);
1944 command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1948 return ERROR_COMMAND_SYNTAX_ERROR;
1954 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1957 return ERROR_COMMAND_SYNTAX_ERROR;
1962 int retval = parse_uint(args[0], &ms);
1963 if (ERROR_OK != retval)
1965 command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1966 return ERROR_COMMAND_SYNTAX_ERROR;
1968 // convert seconds (given) to milliseconds (needed)
1972 target_t *target = get_current_target(cmd_ctx);
1973 return target_wait_state(target, TARGET_HALTED, ms);
1976 /* wait for target state to change. The trick here is to have a low
1977 * latency for short waits and not to suck up all the CPU time
1980 * After 500ms, keep_alive() is invoked
1982 int target_wait_state(target_t *target, enum target_state state, int ms)
1985 long long then = 0, cur;
1990 if ((retval = target_poll(target)) != ERROR_OK)
1992 if (target->state == state)
2000 then = timeval_ms();
2001 LOG_DEBUG("waiting for target %s...",
2002 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2010 if ((cur-then) > ms)
2012 LOG_ERROR("timed out while waiting for target %s",
2013 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2021 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2025 target_t *target = get_current_target(cmd_ctx);
2026 int retval = target_halt(target);
2027 if (ERROR_OK != retval)
2033 retval = parse_uint(args[0], &wait);
2034 if (ERROR_OK != retval)
2035 return ERROR_COMMAND_SYNTAX_ERROR;
2040 return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
2043 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2045 target_t *target = get_current_target(cmd_ctx);
2047 LOG_USER("requesting target halt and executing a soft reset");
2049 target->type->soft_reset_halt(target);
2054 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2057 return ERROR_COMMAND_SYNTAX_ERROR;
2059 enum target_reset_mode reset_mode = RESET_RUN;
2063 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2064 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2065 return ERROR_COMMAND_SYNTAX_ERROR;
2067 reset_mode = n->value;
2070 /* reset *all* targets */
2071 return target_process_reset(cmd_ctx, reset_mode);
2075 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2079 return ERROR_COMMAND_SYNTAX_ERROR;
2081 target_t *target = get_current_target(cmd_ctx);
2082 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2084 /* with no args, resume from current pc, addr = 0,
2085 * with one arguments, addr = args[0],
2086 * handle breakpoints, not debugging */
2090 int retval = parse_u32(args[0], &addr);
2091 if (ERROR_OK != retval)
2096 return target_resume(target, current, addr, 1, 0);
2099 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2102 return ERROR_COMMAND_SYNTAX_ERROR;
2106 /* with no args, step from current pc, addr = 0,
2107 * with one argument addr = args[0],
2108 * handle breakpoints, debugging */
2113 int retval = parse_u32(args[0], &addr);
2114 if (ERROR_OK != retval)
2119 target_t *target = get_current_target(cmd_ctx);
2121 return target->type->step(target, current_pc, addr, 1);
2124 static void handle_md_output(struct command_context_s *cmd_ctx,
2125 struct target_s *target, uint32_t address, unsigned size,
2126 unsigned count, const uint8_t *buffer)
2128 const unsigned line_bytecnt = 32;
2129 unsigned line_modulo = line_bytecnt / size;
2131 char output[line_bytecnt * 4 + 1];
2132 unsigned output_len = 0;
2134 const char *value_fmt;
2136 case 4: value_fmt = "%8.8x "; break;
2137 case 2: value_fmt = "%4.2x "; break;
2138 case 1: value_fmt = "%2.2x "; break;
2140 LOG_ERROR("invalid memory read size: %u", size);
2144 for (unsigned i = 0; i < count; i++)
2146 if (i % line_modulo == 0)
2148 output_len += snprintf(output + output_len,
2149 sizeof(output) - output_len,
2151 (unsigned)(address + (i*size)));
2155 const uint8_t *value_ptr = buffer + i * size;
2157 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2158 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2159 case 1: value = *value_ptr;
2161 output_len += snprintf(output + output_len,
2162 sizeof(output) - output_len,
2165 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2167 command_print(cmd_ctx, "%s", output);
2173 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2176 return ERROR_COMMAND_SYNTAX_ERROR;
2180 case 'w': size = 4; break;
2181 case 'h': size = 2; break;
2182 case 'b': size = 1; break;
2183 default: return ERROR_COMMAND_SYNTAX_ERROR;
2187 int retval = parse_u32(args[0], &address);
2188 if (ERROR_OK != retval)
2194 retval = parse_uint(args[1], &count);
2195 if (ERROR_OK != retval)
2199 uint8_t *buffer = calloc(count, size);
2201 target_t *target = get_current_target(cmd_ctx);
2202 retval = target_read_memory(target,
2203 address, size, count, buffer);
2204 if (ERROR_OK == retval)
2205 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2212 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2214 if ((argc < 2) || (argc > 3))
2215 return ERROR_COMMAND_SYNTAX_ERROR;
2218 int retval = parse_u32(args[0], &address);
2219 if (ERROR_OK != retval)
2223 retval = parse_u32(args[1], &value);
2224 if (ERROR_OK != retval)
2230 retval = parse_uint(args[2], &count);
2231 if (ERROR_OK != retval)
2235 target_t *target = get_current_target(cmd_ctx);
2237 uint8_t value_buf[4];
2242 target_buffer_set_u32(target, value_buf, value);
2246 target_buffer_set_u16(target, value_buf, value);
2250 value_buf[0] = value;
2253 return ERROR_COMMAND_SYNTAX_ERROR;
2255 for (unsigned i = 0; i < count; i++)
2257 retval = target_write_memory(target,
2258 address + i * wordsize, wordsize, 1, value_buf);
2259 if (ERROR_OK != retval)
2268 static int parse_load_image_command_args(char **args, int argc,
2269 image_t *image, uint32_t *min_address, uint32_t *max_address)
2271 if (argc < 1 || argc > 5)
2272 return ERROR_COMMAND_SYNTAX_ERROR;
2274 /* a base address isn't always necessary,
2275 * default to 0x0 (i.e. don't relocate) */
2279 int retval = parse_u32(args[1], &addr);
2280 if (ERROR_OK != retval)
2281 return ERROR_COMMAND_SYNTAX_ERROR;
2282 image->base_address = addr;
2283 image->base_address_set = 1;
2286 image->base_address_set = 0;
2288 image->start_address_set = 0;
2292 int retval = parse_u32(args[3], min_address);
2293 if (ERROR_OK != retval)
2294 return ERROR_COMMAND_SYNTAX_ERROR;
2298 int retval = parse_u32(args[4], max_address);
2299 if (ERROR_OK != retval)
2300 return ERROR_COMMAND_SYNTAX_ERROR;
2301 // use size (given) to find max (required)
2302 *max_address += *min_address;
2305 if (*min_address > *max_address)
2306 return ERROR_COMMAND_SYNTAX_ERROR;
2311 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2315 uint32_t image_size;
2316 uint32_t min_address = 0;
2317 uint32_t max_address = 0xffffffff;
2323 duration_t duration;
2324 char *duration_text;
2326 int retval = parse_load_image_command_args(args, argc,
2327 &image, &min_address, &max_address);
2328 if (ERROR_OK != retval)
2331 target_t *target = get_current_target(cmd_ctx);
2332 duration_start_measure(&duration);
2334 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2341 for (i = 0; i < image.num_sections; i++)
2343 buffer = malloc(image.sections[i].size);
2346 command_print(cmd_ctx,
2347 "error allocating buffer for section (%d bytes)",
2348 (int)(image.sections[i].size));
2352 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2358 uint32_t offset = 0;
2359 uint32_t length = buf_cnt;
2361 /* DANGER!!! beware of unsigned comparision here!!! */
2363 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2364 (image.sections[i].base_address < max_address))
2366 if (image.sections[i].base_address < min_address)
2368 /* clip addresses below */
2369 offset += min_address-image.sections[i].base_address;
2373 if (image.sections[i].base_address + buf_cnt > max_address)
2375 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2378 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2383 image_size += length;
2384 command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2385 (unsigned int)length,
2386 image.sections[i].base_address + offset);
2392 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2394 image_close(&image);
2398 if (retval == ERROR_OK)
2400 command_print(cmd_ctx, "downloaded %u byte in %s",
2401 (unsigned int)image_size,
2404 free(duration_text);
2406 image_close(&image);
2412 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2416 uint8_t buffer[560];
2419 duration_t duration;
2420 char *duration_text;
2422 target_t *target = get_current_target(cmd_ctx);
2426 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2431 int retval = parse_u32(args[1], &address);
2432 if (ERROR_OK != retval)
2436 retval = parse_u32(args[2], &size);
2437 if (ERROR_OK != retval)
2440 if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2445 duration_start_measure(&duration);
2449 uint32_t size_written;
2450 uint32_t this_run_size = (size > 560) ? 560 : size;
2452 retval = target_read_buffer(target, address, this_run_size, buffer);
2453 if (retval != ERROR_OK)
2458 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2459 if (retval != ERROR_OK)
2464 size -= this_run_size;
2465 address += this_run_size;
2468 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2471 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2474 if (retval == ERROR_OK)
2476 command_print(cmd_ctx, "dumped %lld byte in %s",
2477 fileio.size, duration_text);
2478 free(duration_text);
2484 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2488 uint32_t image_size;
2490 int retval, retvaltemp;
2491 uint32_t checksum = 0;
2492 uint32_t mem_checksum = 0;
2496 duration_t duration;
2497 char *duration_text;
2499 target_t *target = get_current_target(cmd_ctx);
2503 return ERROR_COMMAND_SYNTAX_ERROR;
2508 LOG_ERROR("no target selected");
2512 duration_start_measure(&duration);
2517 retval = parse_u32(args[1], &addr);
2518 if (ERROR_OK != retval)
2519 return ERROR_COMMAND_SYNTAX_ERROR;
2520 image.base_address = addr;
2521 image.base_address_set = 1;
2525 image.base_address_set = 0;
2526 image.base_address = 0x0;
2529 image.start_address_set = 0;
2531 if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2538 for (i = 0; i < image.num_sections; i++)
2540 buffer = malloc(image.sections[i].size);
2543 command_print(cmd_ctx,
2544 "error allocating buffer for section (%d bytes)",
2545 (int)(image.sections[i].size));
2548 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2556 /* calculate checksum of image */
2557 image_calculate_checksum(buffer, buf_cnt, &checksum);
2559 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2560 if (retval != ERROR_OK)
2566 if (checksum != mem_checksum)
2568 /* failed crc checksum, fall back to a binary compare */
2571 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2573 data = (uint8_t*)malloc(buf_cnt);
2575 /* Can we use 32bit word accesses? */
2577 int count = buf_cnt;
2578 if ((count % 4) == 0)
2583 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2584 if (retval == ERROR_OK)
2587 for (t = 0; t < buf_cnt; t++)
2589 if (data[t] != buffer[t])
2591 command_print(cmd_ctx,
2592 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2593 (unsigned)(t + image.sections[i].base_address),
2598 retval = ERROR_FAIL;
2612 command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2613 image.sections[i].base_address,
2618 image_size += buf_cnt;
2622 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2624 image_close(&image);
2628 if (retval == ERROR_OK)
2630 command_print(cmd_ctx, "verified %u bytes in %s",
2631 (unsigned int)image_size,
2634 free(duration_text);
2636 image_close(&image);
2641 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2643 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2646 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2648 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2651 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2653 target_t *target = get_current_target(cmd_ctx);
2654 breakpoint_t *breakpoint = target->breakpoints;
2657 if (breakpoint->type == BKPT_SOFT)
2659 char* buf = buf_to_str(breakpoint->orig_instr,
2660 breakpoint->length, 16);
2661 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2662 breakpoint->address,
2664 breakpoint->set, buf);
2669 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2670 breakpoint->address,
2671 breakpoint->length, breakpoint->set);
2674 breakpoint = breakpoint->next;
2679 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2680 uint32_t addr, uint32_t length, int hw)
2682 target_t *target = get_current_target(cmd_ctx);
2683 int retval = breakpoint_add(target, addr, length, hw);
2684 if (ERROR_OK == retval)
2685 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2687 LOG_ERROR("Failure setting breakpoint");
2691 static int handle_bp_command(struct command_context_s *cmd_ctx,
2692 char *cmd, char **args, int argc)
2695 return handle_bp_command_list(cmd_ctx);
2697 if (argc < 2 || argc > 3)
2699 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2700 return ERROR_COMMAND_SYNTAX_ERROR;
2704 int retval = parse_u32(args[0], &addr);
2705 if (ERROR_OK != retval)
2709 retval = parse_u32(args[1], &length);
2710 if (ERROR_OK != retval)
2716 if (strcmp(args[2], "hw") == 0)
2719 return ERROR_COMMAND_SYNTAX_ERROR;
2722 return handle_bp_command_set(cmd_ctx, addr, length, hw);
2725 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2728 return ERROR_COMMAND_SYNTAX_ERROR;
2731 int retval = parse_u32(args[0], &addr);
2732 if (ERROR_OK != retval)
2735 target_t *target = get_current_target(cmd_ctx);
2736 breakpoint_remove(target, addr);
2741 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2743 target_t *target = get_current_target(cmd_ctx);
2747 watchpoint_t *watchpoint = target->watchpoints;
2751 command_print(cmd_ctx,
2752 "address: 0x%8.8" PRIx32 ", len: 0x%8.8x, r/w/a: %i, value: 0x%8.8" PRIx32 ", mask: 0x%8.8" PRIx32 "",
2753 watchpoint->address,
2755 (int)(watchpoint->rw),
2758 watchpoint = watchpoint->next;
2763 enum watchpoint_rw type = WPT_ACCESS;
2765 uint32_t length = 0;
2766 uint32_t data_value = 0x0;
2767 uint32_t data_mask = 0xffffffff;
2773 retval = parse_u32(args[4], &data_mask);
2774 if (ERROR_OK != retval)
2778 retval = parse_u32(args[3], &data_value);
2779 if (ERROR_OK != retval)
2795 LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2796 return ERROR_COMMAND_SYNTAX_ERROR;
2800 retval = parse_u32(args[1], &length);
2801 if (ERROR_OK != retval)
2803 retval = parse_u32(args[0], &addr);
2804 if (ERROR_OK != retval)
2809 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2810 return ERROR_COMMAND_SYNTAX_ERROR;
2813 retval = watchpoint_add(target, addr, length, type,
2814 data_value, data_mask);
2815 if (ERROR_OK != retval)
2816 LOG_ERROR("Failure setting watchpoints");
2821 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2824 return ERROR_COMMAND_SYNTAX_ERROR;
2827 int retval = parse_u32(args[0], &addr);
2828 if (ERROR_OK != retval)
2831 target_t *target = get_current_target(cmd_ctx);
2832 watchpoint_remove(target, addr);
2839 * Translate a virtual address to a physical address.
2841 * The low-level target implementation must have logged a detailed error
2842 * which is forwarded to telnet/GDB session.
2844 static int handle_virt2phys_command(command_context_t *cmd_ctx,
2845 char *cmd, char **args, int argc)
2848 return ERROR_COMMAND_SYNTAX_ERROR;
2851 int retval = parse_u32(args[0], &va);
2852 if (ERROR_OK != retval)
2856 target_t *target = get_current_target(cmd_ctx);
2857 retval = target->type->virt2phys(target, va, &pa);
2858 if (retval == ERROR_OK)
2859 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2864 static void writeData(FILE *f, const void *data, size_t len)
2866 size_t written = fwrite(data, 1, len, f);
2868 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2871 static void writeLong(FILE *f, int l)
2874 for (i = 0; i < 4; i++)
2876 char c = (l >> (i*8))&0xff;
2877 writeData(f, &c, 1);
2882 static void writeString(FILE *f, char *s)
2884 writeData(f, s, strlen(s));
2887 /* Dump a gmon.out histogram file. */
2888 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
2891 FILE *f = fopen(filename, "w");
2894 writeString(f, "gmon");
2895 writeLong(f, 0x00000001); /* Version */
2896 writeLong(f, 0); /* padding */
2897 writeLong(f, 0); /* padding */
2898 writeLong(f, 0); /* padding */
2900 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2901 writeData(f, &zero, 1);
2903 /* figure out bucket size */
2904 uint32_t min = samples[0];
2905 uint32_t max = samples[0];
2906 for (i = 0; i < sampleNum; i++)
2908 if (min > samples[i])
2912 if (max < samples[i])
2918 int addressSpace = (max-min + 1);
2920 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2921 uint32_t length = addressSpace;
2922 if (length > maxBuckets)
2924 length = maxBuckets;
2926 int *buckets = malloc(sizeof(int)*length);
2927 if (buckets == NULL)
2932 memset(buckets, 0, sizeof(int)*length);
2933 for (i = 0; i < sampleNum;i++)
2935 uint32_t address = samples[i];
2936 long long a = address-min;
2937 long long b = length-1;
2938 long long c = addressSpace-1;
2939 int index = (a*b)/c; /* danger!!!! int32 overflows */
2943 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2944 writeLong(f, min); /* low_pc */
2945 writeLong(f, max); /* high_pc */
2946 writeLong(f, length); /* # of samples */
2947 writeLong(f, 64000000); /* 64MHz */
2948 writeString(f, "seconds");
2949 for (i = 0; i < (15-strlen("seconds")); i++)
2950 writeData(f, &zero, 1);
2951 writeString(f, "s");
2953 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2955 char *data = malloc(2*length);
2958 for (i = 0; i < length;i++)
2967 data[i*2 + 1]=(val >> 8)&0xff;
2970 writeData(f, data, length * 2);
2980 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2981 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2983 target_t *target = get_current_target(cmd_ctx);
2984 struct timeval timeout, now;
2986 gettimeofday(&timeout, NULL);
2989 return ERROR_COMMAND_SYNTAX_ERROR;
2992 int retval = parse_uint(args[0], &offset);
2993 if (ERROR_OK != retval)
2996 timeval_add_time(&timeout, offset, 0);
2998 command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3000 static const int maxSample = 10000;
3001 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3002 if (samples == NULL)
3006 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3007 reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
3011 target_poll(target);
3012 if (target->state == TARGET_HALTED)
3014 uint32_t t=*((uint32_t *)reg->value);
3015 samples[numSamples++]=t;
3016 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3017 target_poll(target);
3018 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3019 } else if (target->state == TARGET_RUNNING)
3021 /* We want to quickly sample the PC. */
3022 if ((retval = target_halt(target)) != ERROR_OK)
3029 command_print(cmd_ctx, "Target not halted or running");
3033 if (retval != ERROR_OK)
3038 gettimeofday(&now, NULL);
3039 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3041 command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3042 if ((retval = target_poll(target)) != ERROR_OK)
3047 if (target->state == TARGET_HALTED)
3049 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3051 if ((retval = target_poll(target)) != ERROR_OK)
3056 writeGmon(samples, numSamples, args[1]);
3057 command_print(cmd_ctx, "Wrote %s", args[1]);
3066 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3069 Jim_Obj *nameObjPtr, *valObjPtr;
3072 namebuf = alloc_printf("%s(%d)", varname, idx);
3076 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3077 valObjPtr = Jim_NewIntObj(interp, val);
3078 if (!nameObjPtr || !valObjPtr)
3084 Jim_IncrRefCount(nameObjPtr);
3085 Jim_IncrRefCount(valObjPtr);
3086 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3087 Jim_DecrRefCount(interp, nameObjPtr);
3088 Jim_DecrRefCount(interp, valObjPtr);
3090 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3094 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3096 command_context_t *context;
3099 context = Jim_GetAssocData(interp, "context");
3100 if (context == NULL)
3102 LOG_ERROR("mem2array: no command context");
3105 target = get_current_target(context);
3108 LOG_ERROR("mem2array: no current target");
3112 return target_mem2array(interp, target, argc-1, argv + 1);
3115 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3123 const char *varname;
3124 uint8_t buffer[4096];
3128 /* argv[1] = name of array to receive the data
3129 * argv[2] = desired width
3130 * argv[3] = memory address
3131 * argv[4] = count of times to read
3134 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3137 varname = Jim_GetString(argv[0], &len);
3138 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3140 e = Jim_GetLong(interp, argv[1], &l);
3146 e = Jim_GetLong(interp, argv[2], &l);
3151 e = Jim_GetLong(interp, argv[3], &l);
3167 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3168 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3172 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3173 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3176 if ((addr + (len * width)) < addr) {
3177 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3178 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3181 /* absurd transfer size? */
3183 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3184 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3189 ((width == 2) && ((addr & 1) == 0)) ||
3190 ((width == 4) && ((addr & 3) == 0))) {
3194 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3195 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3198 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3209 /* Slurp... in buffer size chunks */
3211 count = len; /* in objects.. */
3212 if (count > (sizeof(buffer)/width)) {
3213 count = (sizeof(buffer)/width);
3216 retval = target_read_memory(target, addr, width, count, buffer);
3217 if (retval != ERROR_OK) {
3219 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3223 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3224 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3228 v = 0; /* shut up gcc */
3229 for (i = 0 ;i < count ;i++, n++) {
3232 v = target_buffer_get_u32(target, &buffer[i*width]);
3235 v = target_buffer_get_u16(target, &buffer[i*width]);
3238 v = buffer[i] & 0x0ff;
3241 new_int_array_element(interp, varname, n, v);
3247 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3252 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3255 Jim_Obj *nameObjPtr, *valObjPtr;
3259 namebuf = alloc_printf("%s(%d)", varname, idx);
3263 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3270 Jim_IncrRefCount(nameObjPtr);
3271 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3272 Jim_DecrRefCount(interp, nameObjPtr);
3274 if (valObjPtr == NULL)
3277 result = Jim_GetLong(interp, valObjPtr, &l);
3278 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3283 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3285 command_context_t *context;
3288 context = Jim_GetAssocData(interp, "context");
3289 if (context == NULL) {
3290 LOG_ERROR("array2mem: no command context");
3293 target = get_current_target(context);
3294 if (target == NULL) {
3295 LOG_ERROR("array2mem: no current target");
3299 return target_array2mem(interp,target, argc-1, argv + 1);
3302 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3310 const char *varname;
3311 uint8_t buffer[4096];
3315 /* argv[1] = name of array to get the data
3316 * argv[2] = desired width
3317 * argv[3] = memory address
3318 * argv[4] = count to write
3321 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3324 varname = Jim_GetString(argv[0], &len);
3325 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3327 e = Jim_GetLong(interp, argv[1], &l);
3333 e = Jim_GetLong(interp, argv[2], &l);
3338 e = Jim_GetLong(interp, argv[3], &l);
3354 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3355 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3359 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3360 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3363 if ((addr + (len * width)) < addr) {
3364 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3365 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3368 /* absurd transfer size? */
3370 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3371 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3376 ((width == 2) && ((addr & 1) == 0)) ||
3377 ((width == 4) && ((addr & 3) == 0))) {
3381 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3382 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3385 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3396 /* Slurp... in buffer size chunks */
3398 count = len; /* in objects.. */
3399 if (count > (sizeof(buffer)/width)) {
3400 count = (sizeof(buffer)/width);
3403 v = 0; /* shut up gcc */
3404 for (i = 0 ;i < count ;i++, n++) {
3405 get_int_array_element(interp, varname, n, &v);
3408 target_buffer_set_u32(target, &buffer[i*width], v);
3411 target_buffer_set_u16(target, &buffer[i*width], v);
3414 buffer[i] = v & 0x0ff;
3420 retval = target_write_memory(target, addr, width, count, buffer);
3421 if (retval != ERROR_OK) {
3423 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3427 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3428 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3434 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3439 void target_all_handle_event(enum target_event e)
3443 LOG_DEBUG("**all*targets: event: %d, %s",
3445 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3447 target = all_targets;
3449 target_handle_event(target, e);
3450 target = target->next;
3455 /* FIX? should we propagate errors here rather than printing them
3458 void target_handle_event(target_t *target, enum target_event e)
3460 target_event_action_t *teap;
3462 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3463 if (teap->event == e) {
3464 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3465 target->target_number,
3467 target_get_name(target),
3469 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3470 Jim_GetString(teap->body, NULL));
3471 if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3473 Jim_PrintErrorMessage(interp);
3479 enum target_cfg_param {
3482 TCFG_WORK_AREA_VIRT,
3483 TCFG_WORK_AREA_PHYS,
3484 TCFG_WORK_AREA_SIZE,
3485 TCFG_WORK_AREA_BACKUP,
3488 TCFG_CHAIN_POSITION,
3491 static Jim_Nvp nvp_config_opts[] = {
3492 { .name = "-type", .value = TCFG_TYPE },
3493 { .name = "-event", .value = TCFG_EVENT },
3494 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3495 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3496 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3497 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3498 { .name = "-endian" , .value = TCFG_ENDIAN },
3499 { .name = "-variant", .value = TCFG_VARIANT },
3500 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3502 { .name = NULL, .value = -1 }
3505 static int target_configure(Jim_GetOptInfo *goi, target_t *target)
3513 /* parse config or cget options ... */
3514 while (goi->argc > 0) {
3515 Jim_SetEmptyResult(goi->interp);
3516 /* Jim_GetOpt_Debug(goi); */
3518 if (target->type->target_jim_configure) {
3519 /* target defines a configure function */
3520 /* target gets first dibs on parameters */
3521 e = (*(target->type->target_jim_configure))(target, goi);
3530 /* otherwise we 'continue' below */
3532 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3534 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3540 if (goi->isconfigure) {
3541 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3545 if (goi->argc != 0) {
3546 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3550 Jim_SetResultString(goi->interp, target_get_name(target), -1);
3554 if (goi->argc == 0) {
3555 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3559 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3561 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3565 if (goi->isconfigure) {
3566 if (goi->argc != 1) {
3567 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3571 if (goi->argc != 0) {
3572 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3578 target_event_action_t *teap;
3580 teap = target->event_action;
3581 /* replace existing? */
3583 if (teap->event == (enum target_event)n->value) {
3589 if (goi->isconfigure) {
3590 bool replace = true;
3593 teap = calloc(1, sizeof(*teap));
3596 teap->event = n->value;
3597 Jim_GetOpt_Obj(goi, &o);
3599 Jim_DecrRefCount(interp, teap->body);
3601 teap->body = Jim_DuplicateObj(goi->interp, o);
3604 * Tcl/TK - "tk events" have a nice feature.
3605 * See the "BIND" command.
3606 * We should support that here.
3607 * You can specify %X and %Y in the event code.
3608 * The idea is: %T - target name.
3609 * The idea is: %N - target number
3610 * The idea is: %E - event name.
3612 Jim_IncrRefCount(teap->body);
3616 /* add to head of event list */
3617 teap->next = target->event_action;
3618 target->event_action = teap;
3620 Jim_SetEmptyResult(goi->interp);
3624 Jim_SetEmptyResult(goi->interp);
3626 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3633 case TCFG_WORK_AREA_VIRT:
3634 if (goi->isconfigure) {
3635 target_free_all_working_areas(target);
3636 e = Jim_GetOpt_Wide(goi, &w);
3640 target->working_area_virt = w;
3642 if (goi->argc != 0) {
3646 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3650 case TCFG_WORK_AREA_PHYS:
3651 if (goi->isconfigure) {
3652 target_free_all_working_areas(target);
3653 e = Jim_GetOpt_Wide(goi, &w);
3657 target->working_area_phys = w;
3659 if (goi->argc != 0) {
3663 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3667 case TCFG_WORK_AREA_SIZE:
3668 if (goi->isconfigure) {
3669 target_free_all_working_areas(target);
3670 e = Jim_GetOpt_Wide(goi, &w);
3674 target->working_area_size = w;
3676 if (goi->argc != 0) {
3680 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3684 case TCFG_WORK_AREA_BACKUP:
3685 if (goi->isconfigure) {
3686 target_free_all_working_areas(target);
3687 e = Jim_GetOpt_Wide(goi, &w);
3691 /* make this exactly 1 or 0 */
3692 target->backup_working_area = (!!w);
3694 if (goi->argc != 0) {
3698 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3699 /* loop for more e*/
3703 if (goi->isconfigure) {
3704 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3706 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3709 target->endianness = n->value;
3711 if (goi->argc != 0) {
3715 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3716 if (n->name == NULL) {
3717 target->endianness = TARGET_LITTLE_ENDIAN;
3718 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3720 Jim_SetResultString(goi->interp, n->name, -1);
3725 if (goi->isconfigure) {
3726 if (goi->argc < 1) {
3727 Jim_SetResult_sprintf(goi->interp,
3732 if (target->variant) {
3733 free((void *)(target->variant));
3735 e = Jim_GetOpt_String(goi, &cp, NULL);
3736 target->variant = strdup(cp);
3738 if (goi->argc != 0) {
3742 Jim_SetResultString(goi->interp, target->variant,-1);
3745 case TCFG_CHAIN_POSITION:
3746 if (goi->isconfigure) {
3749 target_free_all_working_areas(target);
3750 e = Jim_GetOpt_Obj(goi, &o);
3754 tap = jtag_tap_by_jim_obj(goi->interp, o);
3758 /* make this exactly 1 or 0 */
3761 if (goi->argc != 0) {
3765 Jim_SetResultString(interp, target->tap->dotted_name, -1);
3766 /* loop for more e*/
3769 } /* while (goi->argc) */
3772 /* done - we return */
3776 /** this is the 'tcl' handler for the target specific command */
3777 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3782 uint8_t target_buf[32];
3785 struct command_context_s *cmd_ctx;
3792 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3793 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3794 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3795 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3803 TS_CMD_INVOKE_EVENT,
3806 static const Jim_Nvp target_options[] = {
3807 { .name = "configure", .value = TS_CMD_CONFIGURE },
3808 { .name = "cget", .value = TS_CMD_CGET },
3809 { .name = "mww", .value = TS_CMD_MWW },
3810 { .name = "mwh", .value = TS_CMD_MWH },
3811 { .name = "mwb", .value = TS_CMD_MWB },
3812 { .name = "mdw", .value = TS_CMD_MDW },
3813 { .name = "mdh", .value = TS_CMD_MDH },
3814 { .name = "mdb", .value = TS_CMD_MDB },
3815 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3816 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3817 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3818 { .name = "curstate", .value = TS_CMD_CURSTATE },
3820 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3821 { .name = "arp_poll", .value = TS_CMD_POLL },
3822 { .name = "arp_reset", .value = TS_CMD_RESET },
3823 { .name = "arp_halt", .value = TS_CMD_HALT },
3824 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3825 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3827 { .name = NULL, .value = -1 },
3830 /* go past the "command" */
3831 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3833 target = Jim_CmdPrivData(goi.interp);
3834 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3836 /* commands here are in an NVP table */
3837 e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3839 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3842 /* Assume blank result */
3843 Jim_SetEmptyResult(goi.interp);
3846 case TS_CMD_CONFIGURE:
3848 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3851 goi.isconfigure = 1;
3852 return target_configure(&goi, target);
3854 // some things take params
3856 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3859 goi.isconfigure = 0;
3860 return target_configure(&goi, target);
3868 * argv[3] = optional count.
3871 if ((goi.argc == 2) || (goi.argc == 3)) {
3875 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3879 e = Jim_GetOpt_Wide(&goi, &a);
3884 e = Jim_GetOpt_Wide(&goi, &b);
3888 if (goi.argc == 3) {
3889 e = Jim_GetOpt_Wide(&goi, &c);
3899 target_buffer_set_u32(target, target_buf, b);
3903 target_buffer_set_u16(target, target_buf, b);
3907 target_buffer_set_u8(target, target_buf, b);
3911 for (x = 0 ; x < c ; x++) {
3912 e = target_write_memory(target, a, b, 1, target_buf);
3913 if (e != ERROR_OK) {
3914 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3927 /* argv[0] = command
3929 * argv[2] = optional count
3931 if ((goi.argc == 2) || (goi.argc == 3)) {
3932 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3935 e = Jim_GetOpt_Wide(&goi, &a);
3940 e = Jim_GetOpt_Wide(&goi, &c);
3947 b = 1; /* shut up gcc */
3960 /* convert to "bytes" */
3962 /* count is now in 'BYTES' */
3968 e = target_read_memory(target, a, b, y / b, target_buf);
3969 if (e != ERROR_OK) {
3970 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
3974 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
3977 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
3978 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
3979 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
3981 for (; (x < 16) ; x += 4) {
3982 Jim_fprintf(interp, interp->cookie_stdout, " ");
3986 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
3987 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
3988 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
3990 for (; (x < 16) ; x += 2) {
3991 Jim_fprintf(interp, interp->cookie_stdout, " ");
3996 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
3997 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
3998 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4000 for (; (x < 16) ; x += 1) {
4001 Jim_fprintf(interp, interp->cookie_stdout, " ");
4005 /* ascii-ify the bytes */
4006 for (x = 0 ; x < y ; x++) {
4007 if ((target_buf[x] >= 0x20) &&
4008 (target_buf[x] <= 0x7e)) {
4012 target_buf[x] = '.';
4017 target_buf[x] = ' ';
4022 /* print - with a newline */
4023 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4029 case TS_CMD_MEM2ARRAY:
4030 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4032 case TS_CMD_ARRAY2MEM:
4033 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4035 case TS_CMD_EXAMINE:
4037 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4040 if (!target->tap->enabled)
4041 goto err_tap_disabled;
4042 e = target->type->examine(target);
4043 if (e != ERROR_OK) {
4044 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4050 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4053 if (!target->tap->enabled)
4054 goto err_tap_disabled;
4055 if (!(target_was_examined(target))) {
4056 e = ERROR_TARGET_NOT_EXAMINED;
4058 e = target->type->poll(target);
4060 if (e != ERROR_OK) {
4061 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4068 if (goi.argc != 2) {
4069 Jim_WrongNumArgs(interp, 2, argv,
4070 "([tT]|[fF]|assert|deassert) BOOL");
4073 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4075 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4078 /* the halt or not param */
4079 e = Jim_GetOpt_Wide(&goi, &a);
4083 if (!target->tap->enabled)
4084 goto err_tap_disabled;
4085 if (!target->type->assert_reset
4086 || !target->type->deassert_reset) {
4087 Jim_SetResult_sprintf(interp,
4088 "No target-specific reset for %s",
4092 /* determine if we should halt or not. */
4093 target->reset_halt = !!a;
4094 /* When this happens - all workareas are invalid. */
4095 target_free_all_working_areas_restore(target, 0);
4098 if (n->value == NVP_ASSERT) {
4099 e = target->type->assert_reset(target);
4101 e = target->type->deassert_reset(target);
4103 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4106 Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4109 if (!target->tap->enabled)
4110 goto err_tap_disabled;
4111 e = target->type->halt(target);
4112 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4113 case TS_CMD_WAITSTATE:
4114 /* params: <name> statename timeoutmsecs */
4115 if (goi.argc != 2) {
4116 Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4119 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4121 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4124 e = Jim_GetOpt_Wide(&goi, &a);
4128 if (!target->tap->enabled)
4129 goto err_tap_disabled;
4130 e = target_wait_state(target, n->value, a);
4131 if (e != ERROR_OK) {
4132 Jim_SetResult_sprintf(goi.interp,
4133 "target: %s wait %s fails (%d) %s",
4136 e, target_strerror_safe(e));
4141 case TS_CMD_EVENTLIST:
4142 /* List for human, Events defined for this target.
4143 * scripts/programs should use 'name cget -event NAME'
4146 target_event_action_t *teap;
4147 teap = target->event_action;
4148 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4149 target->target_number,
4151 command_print(cmd_ctx, "%-25s | Body", "Event");
4152 command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4154 command_print(cmd_ctx,
4156 Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4157 Jim_GetString(teap->body, NULL));
4160 command_print(cmd_ctx, "***END***");
4163 case TS_CMD_CURSTATE:
4164 if (goi.argc != 0) {
4165 Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4168 Jim_SetResultString(goi.interp,
4169 target_state_name( target ),
4172 case TS_CMD_INVOKE_EVENT:
4173 if (goi.argc != 1) {
4174 Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4177 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4179 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4182 target_handle_event(target, n->value);
4188 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4192 static int target_create(Jim_GetOptInfo *goi)
4201 struct command_context_s *cmd_ctx;
4203 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4204 if (goi->argc < 3) {
4205 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4210 Jim_GetOpt_Obj(goi, &new_cmd);
4211 /* does this command exist? */
4212 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4214 cp = Jim_GetString(new_cmd, NULL);
4215 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4220 e = Jim_GetOpt_String(goi, &cp2, NULL);
4222 /* now does target type exist */
4223 for (x = 0 ; target_types[x] ; x++) {
4224 if (0 == strcmp(cp, target_types[x]->name)) {
4229 if (target_types[x] == NULL) {
4230 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4231 for (x = 0 ; target_types[x] ; x++) {
4232 if (target_types[x + 1]) {
4233 Jim_AppendStrings(goi->interp,
4234 Jim_GetResult(goi->interp),
4235 target_types[x]->name,
4238 Jim_AppendStrings(goi->interp,
4239 Jim_GetResult(goi->interp),
4241 target_types[x]->name,NULL);
4248 target = calloc(1,sizeof(target_t));
4249 /* set target number */
4250 target->target_number = new_target_number();
4252 /* allocate memory for each unique target type */
4253 target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4255 memcpy(target->type, target_types[x], sizeof(target_type_t));
4257 /* will be set by "-endian" */
4258 target->endianness = TARGET_ENDIAN_UNKNOWN;
4260 target->working_area = 0x0;
4261 target->working_area_size = 0x0;
4262 target->working_areas = NULL;
4263 target->backup_working_area = 0;
4265 target->state = TARGET_UNKNOWN;
4266 target->debug_reason = DBG_REASON_UNDEFINED;
4267 target->reg_cache = NULL;
4268 target->breakpoints = NULL;
4269 target->watchpoints = NULL;
4270 target->next = NULL;
4271 target->arch_info = NULL;
4273 target->display = 1;
4275 target->halt_issued = false;
4277 /* initialize trace information */
4278 target->trace_info = malloc(sizeof(trace_t));
4279 target->trace_info->num_trace_points = 0;
4280 target->trace_info->trace_points_size = 0;
4281 target->trace_info->trace_points = NULL;
4282 target->trace_info->trace_history_size = 0;
4283 target->trace_info->trace_history = NULL;
4284 target->trace_info->trace_history_pos = 0;
4285 target->trace_info->trace_history_overflowed = 0;
4287 target->dbgmsg = NULL;
4288 target->dbg_msg_enabled = 0;
4290 target->endianness = TARGET_ENDIAN_UNKNOWN;
4292 /* Do the rest as "configure" options */
4293 goi->isconfigure = 1;
4294 e = target_configure(goi, target);
4296 if (target->tap == NULL)
4298 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4308 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4309 /* default endian to little if not specified */
4310 target->endianness = TARGET_LITTLE_ENDIAN;
4313 /* incase variant is not set */
4314 if (!target->variant)
4315 target->variant = strdup("");
4317 /* create the target specific commands */
4318 if (target->type->register_commands) {
4319 (*(target->type->register_commands))(cmd_ctx);
4321 if (target->type->target_create) {
4322 (*(target->type->target_create))(target, goi->interp);
4325 /* append to end of list */
4328 tpp = &(all_targets);
4330 tpp = &((*tpp)->next);
4335 cp = Jim_GetString(new_cmd, NULL);
4336 target->cmd_name = strdup(cp);
4338 /* now - create the new target name command */
4339 e = Jim_CreateCommand(goi->interp,
4342 tcl_target_func, /* C function */
4343 target, /* private data */
4344 NULL); /* no del proc */
4349 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4353 struct command_context_s *cmd_ctx;
4357 /* TG = target generic */
4365 const char *target_cmds[] = {
4366 "create", "types", "names", "current", "number",
4368 NULL /* terminate */
4371 LOG_DEBUG("Target command params:");
4372 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4374 cmd_ctx = Jim_GetAssocData(interp, "context");
4376 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4378 if (goi.argc == 0) {
4379 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4383 /* Jim_GetOpt_Debug(&goi); */
4384 r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4391 Jim_Panic(goi.interp,"Why am I here?");
4393 case TG_CMD_CURRENT:
4394 if (goi.argc != 0) {
4395 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4398 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4401 if (goi.argc != 0) {
4402 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4405 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4406 for (x = 0 ; target_types[x] ; x++) {
4407 Jim_ListAppendElement(goi.interp,
4408 Jim_GetResult(goi.interp),
4409 Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4413 if (goi.argc != 0) {
4414 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4417 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4418 target = all_targets;
4420 Jim_ListAppendElement(goi.interp,
4421 Jim_GetResult(goi.interp),
4422 Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4423 target = target->next;
4428 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4431 return target_create(&goi);
4434 /* It's OK to remove this mechanism sometime after August 2010 or so */
4435 LOG_WARNING("don't use numbers as target identifiers; use names");
4436 if (goi.argc != 1) {
4437 Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4440 e = Jim_GetOpt_Wide(&goi, &w);
4444 for (x = 0, target = all_targets; target; target = target->next, x++) {
4445 if (target->target_number == w)
4448 if (target == NULL) {
4449 Jim_SetResult_sprintf(goi.interp,
4450 "Target: number %d does not exist", (int)(w));
4453 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4456 if (goi.argc != 0) {
4457 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4460 for (x = 0, target = all_targets; target; target = target->next, x++)
4462 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4478 static int fastload_num;
4479 static struct FastLoad *fastload;
4481 static void free_fastload(void)
4483 if (fastload != NULL)
4486 for (i = 0; i < fastload_num; i++)
4488 if (fastload[i].data)
4489 free(fastload[i].data);
4499 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4503 uint32_t image_size;
4504 uint32_t min_address = 0;
4505 uint32_t max_address = 0xffffffff;
4510 duration_t duration;
4511 char *duration_text;
4513 int retval = parse_load_image_command_args(args, argc,
4514 &image, &min_address, &max_address);
4515 if (ERROR_OK != retval)
4518 duration_start_measure(&duration);
4520 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4527 fastload_num = image.num_sections;
4528 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4529 if (fastload == NULL)
4531 image_close(&image);
4534 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4535 for (i = 0; i < image.num_sections; i++)
4537 buffer = malloc(image.sections[i].size);
4540 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4541 (int)(image.sections[i].size));
4545 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4551 uint32_t offset = 0;
4552 uint32_t length = buf_cnt;
4555 /* DANGER!!! beware of unsigned comparision here!!! */
4557 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4558 (image.sections[i].base_address < max_address))
4560 if (image.sections[i].base_address < min_address)
4562 /* clip addresses below */
4563 offset += min_address-image.sections[i].base_address;
4567 if (image.sections[i].base_address + buf_cnt > max_address)
4569 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4572 fastload[i].address = image.sections[i].base_address + offset;
4573 fastload[i].data = malloc(length);
4574 if (fastload[i].data == NULL)
4579 memcpy(fastload[i].data, buffer + offset, length);
4580 fastload[i].length = length;
4582 image_size += length;
4583 command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4584 (unsigned int)length,
4585 ((unsigned int)(image.sections[i].base_address + offset)));
4591 duration_stop_measure(&duration, &duration_text);
4592 if (retval == ERROR_OK)
4594 command_print(cmd_ctx, "Loaded %u bytes in %s", (unsigned int)image_size, duration_text);
4595 command_print(cmd_ctx, "NB!!! image has not been loaded to target, issue a subsequent 'fast_load' to do so.");
4597 free(duration_text);
4599 image_close(&image);
4601 if (retval != ERROR_OK)
4609 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4612 return ERROR_COMMAND_SYNTAX_ERROR;
4613 if (fastload == NULL)
4615 LOG_ERROR("No image in memory");
4619 int ms = timeval_ms();
4621 int retval = ERROR_OK;
4622 for (i = 0; i < fastload_num;i++)
4624 target_t *target = get_current_target(cmd_ctx);
4625 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4626 (unsigned int)(fastload[i].address),
4627 (unsigned int)(fastload[i].length));
4628 if (retval == ERROR_OK)
4630 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4632 size += fastload[i].length;
4634 int after = timeval_ms();
4635 command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));