1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2009 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
17 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program; if not, write to the *
29 * Free Software Foundation, Inc., *
30 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
31 ***************************************************************************/
37 #include "target_type.h"
38 #include "target_request.h"
39 #include "time_support.h"
46 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
48 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
49 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
52 extern target_type_t arm7tdmi_target;
53 extern target_type_t arm720t_target;
54 extern target_type_t arm9tdmi_target;
55 extern target_type_t arm920t_target;
56 extern target_type_t arm966e_target;
57 extern target_type_t arm926ejs_target;
58 extern target_type_t fa526_target;
59 extern target_type_t feroceon_target;
60 extern target_type_t dragonite_target;
61 extern target_type_t xscale_target;
62 extern target_type_t cortexm3_target;
63 extern target_type_t cortexa8_target;
64 extern target_type_t arm11_target;
65 extern target_type_t mips_m4k_target;
66 extern target_type_t avr_target;
68 target_type_t *target_types[] =
88 target_t *all_targets = NULL;
89 target_event_callback_t *target_event_callbacks = NULL;
90 target_timer_callback_t *target_timer_callbacks = NULL;
92 const Jim_Nvp nvp_assert[] = {
93 { .name = "assert", NVP_ASSERT },
94 { .name = "deassert", NVP_DEASSERT },
95 { .name = "T", NVP_ASSERT },
96 { .name = "F", NVP_DEASSERT },
97 { .name = "t", NVP_ASSERT },
98 { .name = "f", NVP_DEASSERT },
99 { .name = NULL, .value = -1 }
102 const Jim_Nvp nvp_error_target[] = {
103 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
104 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
105 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
106 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
107 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
108 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
109 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
110 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
111 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
112 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
113 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
114 { .value = -1, .name = NULL }
117 const char *target_strerror_safe(int err)
121 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
122 if (n->name == NULL) {
129 static const Jim_Nvp nvp_target_event[] = {
130 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
131 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
133 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
134 { .value = TARGET_EVENT_HALTED, .name = "halted" },
135 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
136 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
137 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
139 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
140 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
142 /* historical name */
144 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
146 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
147 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
148 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
149 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
150 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
151 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
152 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
153 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
154 { .value = TARGET_EVENT_RESET_INIT , .name = "reset-init" },
155 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
157 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
158 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
160 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
161 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
163 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
164 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
166 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
167 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
169 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
170 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
172 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
173 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
174 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
176 { .name = NULL, .value = -1 }
179 const Jim_Nvp nvp_target_state[] = {
180 { .name = "unknown", .value = TARGET_UNKNOWN },
181 { .name = "running", .value = TARGET_RUNNING },
182 { .name = "halted", .value = TARGET_HALTED },
183 { .name = "reset", .value = TARGET_RESET },
184 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
185 { .name = NULL, .value = -1 },
188 const Jim_Nvp nvp_target_debug_reason [] = {
189 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
190 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
191 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
192 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
193 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
194 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
195 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
196 { .name = NULL, .value = -1 },
199 const Jim_Nvp nvp_target_endian[] = {
200 { .name = "big", .value = TARGET_BIG_ENDIAN },
201 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
202 { .name = "be", .value = TARGET_BIG_ENDIAN },
203 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
204 { .name = NULL, .value = -1 },
207 const Jim_Nvp nvp_reset_modes[] = {
208 { .name = "unknown", .value = RESET_UNKNOWN },
209 { .name = "run" , .value = RESET_RUN },
210 { .name = "halt" , .value = RESET_HALT },
211 { .name = "init" , .value = RESET_INIT },
212 { .name = NULL , .value = -1 },
216 target_state_name( target_t *t )
219 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
221 LOG_ERROR("Invalid target state: %d", (int)(t->state));
222 cp = "(*BUG*unknown*BUG*)";
227 /* determine the number of the new target */
228 static int new_target_number(void)
233 /* number is 0 based */
237 if (x < t->target_number) {
238 x = t->target_number;
245 /* read a uint32_t from a buffer in target memory endianness */
246 uint32_t target_buffer_get_u32(target_t *target, const uint8_t *buffer)
248 if (target->endianness == TARGET_LITTLE_ENDIAN)
249 return le_to_h_u32(buffer);
251 return be_to_h_u32(buffer);
254 /* read a uint16_t from a buffer in target memory endianness */
255 uint16_t target_buffer_get_u16(target_t *target, const uint8_t *buffer)
257 if (target->endianness == TARGET_LITTLE_ENDIAN)
258 return le_to_h_u16(buffer);
260 return be_to_h_u16(buffer);
263 /* read a uint8_t from a buffer in target memory endianness */
264 uint8_t target_buffer_get_u8(target_t *target, const uint8_t *buffer)
266 return *buffer & 0x0ff;
269 /* write a uint32_t to a buffer in target memory endianness */
270 void target_buffer_set_u32(target_t *target, uint8_t *buffer, uint32_t value)
272 if (target->endianness == TARGET_LITTLE_ENDIAN)
273 h_u32_to_le(buffer, value);
275 h_u32_to_be(buffer, value);
278 /* write a uint16_t to a buffer in target memory endianness */
279 void target_buffer_set_u16(target_t *target, uint8_t *buffer, uint16_t value)
281 if (target->endianness == TARGET_LITTLE_ENDIAN)
282 h_u16_to_le(buffer, value);
284 h_u16_to_be(buffer, value);
287 /* write a uint8_t to a buffer in target memory endianness */
288 void target_buffer_set_u8(target_t *target, uint8_t *buffer, uint8_t value)
293 /* return a pointer to a configured target; id is name or number */
294 target_t *get_target(const char *id)
298 /* try as tcltarget name */
299 for (target = all_targets; target; target = target->next) {
300 if (target->cmd_name == NULL)
302 if (strcmp(id, target->cmd_name) == 0)
306 /* It's OK to remove this fallback sometime after August 2010 or so */
308 /* no match, try as number */
310 if (parse_uint(id, &num) != ERROR_OK)
313 for (target = all_targets; target; target = target->next) {
314 if (target->target_number == (int)num) {
315 LOG_WARNING("use '%s' as target identifier, not '%u'",
316 target->cmd_name, num);
324 /* returns a pointer to the n-th configured target */
325 static target_t *get_target_by_num(int num)
327 target_t *target = all_targets;
330 if (target->target_number == num) {
333 target = target->next;
339 target_t* get_current_target(command_context_t *cmd_ctx)
341 target_t *target = get_target_by_num(cmd_ctx->current_target);
345 LOG_ERROR("BUG: current_target out of bounds");
352 int target_poll(struct target_s *target)
356 /* We can't poll until after examine */
357 if (!target_was_examined(target))
359 /* Fail silently lest we pollute the log */
363 retval = target->type->poll(target);
364 if (retval != ERROR_OK)
367 if (target->halt_issued)
369 if (target->state == TARGET_HALTED)
371 target->halt_issued = false;
374 long long t = timeval_ms() - target->halt_issued_time;
377 target->halt_issued = false;
378 LOG_INFO("Halt timed out, wake up GDB.");
379 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
387 int target_halt(struct target_s *target)
390 /* We can't poll until after examine */
391 if (!target_was_examined(target))
393 LOG_ERROR("Target not examined yet");
397 retval = target->type->halt(target);
398 if (retval != ERROR_OK)
401 target->halt_issued = true;
402 target->halt_issued_time = timeval_ms();
407 int target_resume(struct target_s *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
411 /* We can't poll until after examine */
412 if (!target_was_examined(target))
414 LOG_ERROR("Target not examined yet");
418 /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
419 * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
422 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
428 int target_process_reset(struct command_context_s *cmd_ctx, enum target_reset_mode reset_mode)
433 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
434 if (n->name == NULL) {
435 LOG_ERROR("invalid reset mode");
439 /* disable polling during reset to make reset event scripts
440 * more predictable, i.e. dr/irscan & pathmove in events will
441 * not have JTAG operations injected into the middle of a sequence.
443 bool save_poll = jtag_poll_get_enabled();
445 jtag_poll_set_enabled(false);
447 sprintf(buf, "ocd_process_reset %s", n->name);
448 retval = Jim_Eval(interp, buf);
450 jtag_poll_set_enabled(save_poll);
452 if (retval != JIM_OK) {
453 Jim_PrintErrorMessage(interp);
457 /* We want any events to be processed before the prompt */
458 retval = target_call_timer_callbacks_now();
463 static int default_virt2phys(struct target_s *target, uint32_t virtual, uint32_t *physical)
469 static int default_mmu(struct target_s *target, int *enabled)
475 static int default_examine(struct target_s *target)
477 target_set_examined(target);
481 int target_examine_one(struct target_s *target)
483 return target->type->examine(target);
486 static int jtag_enable_callback(enum jtag_event event, void *priv)
488 target_t *target = priv;
490 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
493 jtag_unregister_event_callback(jtag_enable_callback, target);
494 return target_examine_one(target);
498 /* Targets that correctly implement init + examine, i.e.
499 * no communication with target during init:
503 int target_examine(void)
505 int retval = ERROR_OK;
508 for (target = all_targets; target; target = target->next)
510 /* defer examination, but don't skip it */
511 if (!target->tap->enabled) {
512 jtag_register_event_callback(jtag_enable_callback,
516 if ((retval = target_examine_one(target)) != ERROR_OK)
521 const char *target_get_name(struct target_s *target)
523 return target->type->name;
526 static int target_write_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
528 if (!target_was_examined(target))
530 LOG_ERROR("Target not examined yet");
533 return target->type->write_memory_imp(target, address, size, count, buffer);
536 static int target_read_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
538 if (!target_was_examined(target))
540 LOG_ERROR("Target not examined yet");
543 return target->type->read_memory_imp(target, address, size, count, buffer);
546 static int target_soft_reset_halt_imp(struct target_s *target)
548 if (!target_was_examined(target))
550 LOG_ERROR("Target not examined yet");
553 if (!target->type->soft_reset_halt_imp) {
554 LOG_ERROR("Target %s does not support soft_reset_halt",
558 return target->type->soft_reset_halt_imp(target);
561 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)
563 if (!target_was_examined(target))
565 LOG_ERROR("Target not examined yet");
568 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);
571 int target_read_memory(struct target_s *target,
572 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
574 return target->type->read_memory(target, address, size, count, buffer);
577 int target_read_phys_memory(struct target_s *target,
578 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
580 return target->type->read_phys_memory(target, address, size, count, buffer);
583 int target_write_memory(struct target_s *target,
584 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
586 return target->type->write_memory(target, address, size, count, buffer);
589 int target_write_phys_memory(struct target_s *target,
590 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
592 return target->type->write_phys_memory(target, address, size, count, buffer);
595 int target_bulk_write_memory(struct target_s *target,
596 uint32_t address, uint32_t count, uint8_t *buffer)
598 return target->type->bulk_write_memory(target, address, count, buffer);
601 int target_add_breakpoint(struct target_s *target,
602 struct breakpoint_s *breakpoint)
604 return target->type->add_breakpoint(target, breakpoint);
606 int target_remove_breakpoint(struct target_s *target,
607 struct breakpoint_s *breakpoint)
609 return target->type->remove_breakpoint(target, breakpoint);
612 int target_add_watchpoint(struct target_s *target,
613 struct watchpoint_s *watchpoint)
615 return target->type->add_watchpoint(target, watchpoint);
617 int target_remove_watchpoint(struct target_s *target,
618 struct watchpoint_s *watchpoint)
620 return target->type->remove_watchpoint(target, watchpoint);
623 int target_get_gdb_reg_list(struct target_s *target,
624 struct reg_s **reg_list[], int *reg_list_size)
626 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
628 int target_step(struct target_s *target,
629 int current, uint32_t address, int handle_breakpoints)
631 return target->type->step(target, current, address, handle_breakpoints);
635 int target_run_algorithm(struct target_s *target,
636 int num_mem_params, mem_param_t *mem_params,
637 int num_reg_params, reg_param_t *reg_param,
638 uint32_t entry_point, uint32_t exit_point,
639 int timeout_ms, void *arch_info)
641 return target->type->run_algorithm(target,
642 num_mem_params, mem_params, num_reg_params, reg_param,
643 entry_point, exit_point, timeout_ms, arch_info);
646 /// @returns @c true if the target has been examined.
647 bool target_was_examined(struct target_s *target)
649 return target->type->examined;
651 /// Sets the @c examined flag for the given target.
652 void target_set_examined(struct target_s *target)
654 target->type->examined = true;
656 // Reset the @c examined flag for the given target.
657 void target_reset_examined(struct target_s *target)
659 target->type->examined = false;
664 static int default_mrc(struct target_s *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
666 LOG_ERROR("Not implemented");
670 static int default_mcr(struct target_s *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
672 LOG_ERROR("Not implemented");
676 static int arm_cp_check(struct target_s *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm)
679 if (!target_was_examined(target))
681 LOG_ERROR("Target not examined yet");
685 if ((cpnum <0) || (cpnum > 15))
687 LOG_ERROR("Illegal co-processor %d", cpnum);
693 LOG_ERROR("Illegal op1");
699 LOG_ERROR("Illegal op2");
705 LOG_ERROR("Illegal CRn");
711 LOG_ERROR("Illegal CRm");
718 int target_mrc(struct target_s *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
722 retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
723 if (retval != ERROR_OK)
726 return target->type->mrc(target, cpnum, op1, op2, CRn, CRm, value);
729 int target_mcr(struct target_s *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
733 retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
734 if (retval != ERROR_OK)
737 return target->type->mcr(target, cpnum, op1, op2, CRn, CRm, value);
740 static int default_read_phys_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
742 LOG_ERROR("Not implemented");
746 static int default_write_phys_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
748 LOG_ERROR("Not implemented");
753 int target_init(struct command_context_s *cmd_ctx)
755 target_t *target = all_targets;
760 target_reset_examined(target);
761 if (target->type->examine == NULL)
763 target->type->examine = default_examine;
766 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
768 LOG_ERROR("target '%s' init failed", target_get_name(target));
772 /* Set up default functions if none are provided by target */
773 if (target->type->virt2phys == NULL)
775 target->type->virt2phys = default_virt2phys;
778 if (target->type->read_phys_memory == NULL)
780 target->type->read_phys_memory = default_read_phys_memory;
783 if (target->type->write_phys_memory == NULL)
785 target->type->write_phys_memory = default_write_phys_memory;
788 if (target->type->mcr == NULL)
790 target->type->mcr = default_mcr;
793 /* FIX! multiple targets will generally register global commands
794 * multiple times. Only register this one if *one* of the
795 * targets need the command. Hmm... make it a command on the
796 * Jim Tcl target object?
798 register_jim(cmd_ctx, "mcr", jim_mcrmrc, "write coprocessor <cpnum> <op1> <op2> <CRn> <CRm> <value>");
801 if (target->type->mrc == NULL)
803 target->type->mrc = default_mrc;
806 register_jim(cmd_ctx, "mrc", jim_mcrmrc, "read coprocessor <cpnum> <op1> <op2> <CRn> <CRm>");
810 /* a non-invasive way(in terms of patches) to add some code that
811 * runs before the type->write/read_memory implementation
813 target->type->write_memory_imp = target->type->write_memory;
814 target->type->write_memory = target_write_memory_imp;
815 target->type->read_memory_imp = target->type->read_memory;
816 target->type->read_memory = target_read_memory_imp;
817 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
818 target->type->soft_reset_halt = target_soft_reset_halt_imp;
819 target->type->run_algorithm_imp = target->type->run_algorithm;
820 target->type->run_algorithm = target_run_algorithm_imp;
822 if (target->type->mmu == NULL)
824 target->type->mmu = default_mmu;
826 target = target->next;
831 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
833 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
840 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
842 target_event_callback_t **callbacks_p = &target_event_callbacks;
844 if (callback == NULL)
846 return ERROR_INVALID_ARGUMENTS;
851 while ((*callbacks_p)->next)
852 callbacks_p = &((*callbacks_p)->next);
853 callbacks_p = &((*callbacks_p)->next);
856 (*callbacks_p) = malloc(sizeof(target_event_callback_t));
857 (*callbacks_p)->callback = callback;
858 (*callbacks_p)->priv = priv;
859 (*callbacks_p)->next = NULL;
864 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
866 target_timer_callback_t **callbacks_p = &target_timer_callbacks;
869 if (callback == NULL)
871 return ERROR_INVALID_ARGUMENTS;
876 while ((*callbacks_p)->next)
877 callbacks_p = &((*callbacks_p)->next);
878 callbacks_p = &((*callbacks_p)->next);
881 (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
882 (*callbacks_p)->callback = callback;
883 (*callbacks_p)->periodic = periodic;
884 (*callbacks_p)->time_ms = time_ms;
886 gettimeofday(&now, NULL);
887 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
888 time_ms -= (time_ms % 1000);
889 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
890 if ((*callbacks_p)->when.tv_usec > 1000000)
892 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
893 (*callbacks_p)->when.tv_sec += 1;
896 (*callbacks_p)->priv = priv;
897 (*callbacks_p)->next = NULL;
902 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
904 target_event_callback_t **p = &target_event_callbacks;
905 target_event_callback_t *c = target_event_callbacks;
907 if (callback == NULL)
909 return ERROR_INVALID_ARGUMENTS;
914 target_event_callback_t *next = c->next;
915 if ((c->callback == callback) && (c->priv == priv))
929 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
931 target_timer_callback_t **p = &target_timer_callbacks;
932 target_timer_callback_t *c = target_timer_callbacks;
934 if (callback == NULL)
936 return ERROR_INVALID_ARGUMENTS;
941 target_timer_callback_t *next = c->next;
942 if ((c->callback == callback) && (c->priv == priv))
956 int target_call_event_callbacks(target_t *target, enum target_event event)
958 target_event_callback_t *callback = target_event_callbacks;
959 target_event_callback_t *next_callback;
961 if (event == TARGET_EVENT_HALTED)
963 /* execute early halted first */
964 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
967 LOG_DEBUG("target event %i (%s)",
969 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
971 target_handle_event(target, event);
975 next_callback = callback->next;
976 callback->callback(target, event, callback->priv);
977 callback = next_callback;
983 static int target_timer_callback_periodic_restart(
984 target_timer_callback_t *cb, struct timeval *now)
986 int time_ms = cb->time_ms;
987 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
988 time_ms -= (time_ms % 1000);
989 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
990 if (cb->when.tv_usec > 1000000)
992 cb->when.tv_usec = cb->when.tv_usec - 1000000;
993 cb->when.tv_sec += 1;
998 static int target_call_timer_callback(target_timer_callback_t *cb,
1001 cb->callback(cb->priv);
1004 return target_timer_callback_periodic_restart(cb, now);
1006 return target_unregister_timer_callback(cb->callback, cb->priv);
1009 static int target_call_timer_callbacks_check_time(int checktime)
1014 gettimeofday(&now, NULL);
1016 target_timer_callback_t *callback = target_timer_callbacks;
1019 // cleaning up may unregister and free this callback
1020 target_timer_callback_t *next_callback = callback->next;
1022 bool call_it = callback->callback &&
1023 ((!checktime && callback->periodic) ||
1024 now.tv_sec > callback->when.tv_sec ||
1025 (now.tv_sec == callback->when.tv_sec &&
1026 now.tv_usec >= callback->when.tv_usec));
1030 int retval = target_call_timer_callback(callback, &now);
1031 if (retval != ERROR_OK)
1035 callback = next_callback;
1041 int target_call_timer_callbacks(void)
1043 return target_call_timer_callbacks_check_time(1);
1046 /* invoke periodic callbacks immediately */
1047 int target_call_timer_callbacks_now(void)
1049 return target_call_timer_callbacks_check_time(0);
1052 int target_alloc_working_area(struct target_s *target, uint32_t size, working_area_t **area)
1054 working_area_t *c = target->working_areas;
1055 working_area_t *new_wa = NULL;
1057 /* Reevaluate working area address based on MMU state*/
1058 if (target->working_areas == NULL)
1063 retval = target->type->mmu(target, &enabled);
1064 if (retval != ERROR_OK)
1070 if (target->working_area_phys_spec) {
1071 LOG_DEBUG("MMU disabled, using physical "
1072 "address for working memory 0x%08x",
1073 (unsigned)target->working_area_phys);
1074 target->working_area = target->working_area_phys;
1076 LOG_ERROR("No working memory available. "
1077 "Specify -work-area-phys to target.");
1078 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1081 if (target->working_area_virt_spec) {
1082 LOG_DEBUG("MMU enabled, using virtual "
1083 "address for working memory 0x%08x",
1084 (unsigned)target->working_area_virt);
1085 target->working_area = target->working_area_virt;
1087 LOG_ERROR("No working memory available. "
1088 "Specify -work-area-virt to target.");
1089 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1094 /* only allocate multiples of 4 byte */
1097 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1098 size = (size + 3) & (~3);
1101 /* see if there's already a matching working area */
1104 if ((c->free) && (c->size == size))
1112 /* if not, allocate a new one */
1115 working_area_t **p = &target->working_areas;
1116 uint32_t first_free = target->working_area;
1117 uint32_t free_size = target->working_area_size;
1119 c = target->working_areas;
1122 first_free += c->size;
1123 free_size -= c->size;
1128 if (free_size < size)
1130 LOG_WARNING("not enough working area available(requested %u, free %u)",
1131 (unsigned)(size), (unsigned)(free_size));
1132 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1135 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1137 new_wa = malloc(sizeof(working_area_t));
1138 new_wa->next = NULL;
1139 new_wa->size = size;
1140 new_wa->address = first_free;
1142 if (target->backup_working_area)
1145 new_wa->backup = malloc(new_wa->size);
1146 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1148 free(new_wa->backup);
1155 new_wa->backup = NULL;
1158 /* put new entry in list */
1162 /* mark as used, and return the new (reused) area */
1167 new_wa->user = area;
1172 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
1177 if (restore && target->backup_working_area)
1180 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1186 /* mark user pointer invalid */
1193 int target_free_working_area(struct target_s *target, working_area_t *area)
1195 return target_free_working_area_restore(target, area, 1);
1198 /* free resources and restore memory, if restoring memory fails,
1199 * free up resources anyway
1201 void target_free_all_working_areas_restore(struct target_s *target, int restore)
1203 working_area_t *c = target->working_areas;
1207 working_area_t *next = c->next;
1208 target_free_working_area_restore(target, c, restore);
1218 target->working_areas = NULL;
1221 void target_free_all_working_areas(struct target_s *target)
1223 target_free_all_working_areas_restore(target, 1);
1226 int target_arch_state(struct target_s *target)
1231 LOG_USER("No target has been configured");
1235 LOG_USER("target state: %s", target_state_name( target ));
1237 if (target->state != TARGET_HALTED)
1240 retval = target->type->arch_state(target);
1244 /* Single aligned words are guaranteed to use 16 or 32 bit access
1245 * mode respectively, otherwise data is handled as quickly as
1248 int target_write_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1251 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1252 (int)size, (unsigned)address);
1254 if (!target_was_examined(target))
1256 LOG_ERROR("Target not examined yet");
1264 if ((address + size - 1) < address)
1266 /* GDB can request this when e.g. PC is 0xfffffffc*/
1267 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1273 if (((address % 2) == 0) && (size == 2))
1275 return target_write_memory(target, address, 2, 1, buffer);
1278 /* handle unaligned head bytes */
1281 uint32_t unaligned = 4 - (address % 4);
1283 if (unaligned > size)
1286 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1289 buffer += unaligned;
1290 address += unaligned;
1294 /* handle aligned words */
1297 int aligned = size - (size % 4);
1299 /* use bulk writes above a certain limit. This may have to be changed */
1302 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1307 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1316 /* handle tail writes of less than 4 bytes */
1319 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1326 /* Single aligned words are guaranteed to use 16 or 32 bit access
1327 * mode respectively, otherwise data is handled as quickly as
1330 int target_read_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1333 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1334 (int)size, (unsigned)address);
1336 if (!target_was_examined(target))
1338 LOG_ERROR("Target not examined yet");
1346 if ((address + size - 1) < address)
1348 /* GDB can request this when e.g. PC is 0xfffffffc*/
1349 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1355 if (((address % 2) == 0) && (size == 2))
1357 return target_read_memory(target, address, 2, 1, buffer);
1360 /* handle unaligned head bytes */
1363 uint32_t unaligned = 4 - (address % 4);
1365 if (unaligned > size)
1368 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1371 buffer += unaligned;
1372 address += unaligned;
1376 /* handle aligned words */
1379 int aligned = size - (size % 4);
1381 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1389 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1392 int aligned = size - (size%2);
1393 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1394 if (retval != ERROR_OK)
1401 /* handle tail writes of less than 4 bytes */
1404 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1411 int target_checksum_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* crc)
1416 uint32_t checksum = 0;
1417 if (!target_was_examined(target))
1419 LOG_ERROR("Target not examined yet");
1423 if ((retval = target->type->checksum_memory(target, address,
1424 size, &checksum)) != ERROR_OK)
1426 buffer = malloc(size);
1429 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1430 return ERROR_INVALID_ARGUMENTS;
1432 retval = target_read_buffer(target, address, size, buffer);
1433 if (retval != ERROR_OK)
1439 /* convert to target endianess */
1440 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1442 uint32_t target_data;
1443 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1444 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1447 retval = image_calculate_checksum(buffer, size, &checksum);
1456 int target_blank_check_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* blank)
1459 if (!target_was_examined(target))
1461 LOG_ERROR("Target not examined yet");
1465 if (target->type->blank_check_memory == 0)
1466 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1468 retval = target->type->blank_check_memory(target, address, size, blank);
1473 int target_read_u32(struct target_s *target, uint32_t address, uint32_t *value)
1475 uint8_t value_buf[4];
1476 if (!target_was_examined(target))
1478 LOG_ERROR("Target not examined yet");
1482 int retval = target_read_memory(target, address, 4, 1, value_buf);
1484 if (retval == ERROR_OK)
1486 *value = target_buffer_get_u32(target, value_buf);
1487 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1494 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1501 int target_read_u16(struct target_s *target, uint32_t address, uint16_t *value)
1503 uint8_t value_buf[2];
1504 if (!target_was_examined(target))
1506 LOG_ERROR("Target not examined yet");
1510 int retval = target_read_memory(target, address, 2, 1, value_buf);
1512 if (retval == ERROR_OK)
1514 *value = target_buffer_get_u16(target, value_buf);
1515 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1522 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1529 int target_read_u8(struct target_s *target, uint32_t address, uint8_t *value)
1531 int retval = target_read_memory(target, address, 1, 1, value);
1532 if (!target_was_examined(target))
1534 LOG_ERROR("Target not examined yet");
1538 if (retval == ERROR_OK)
1540 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1547 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1554 int target_write_u32(struct target_s *target, uint32_t address, uint32_t value)
1557 uint8_t value_buf[4];
1558 if (!target_was_examined(target))
1560 LOG_ERROR("Target not examined yet");
1564 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1568 target_buffer_set_u32(target, value_buf, value);
1569 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1571 LOG_DEBUG("failed: %i", retval);
1577 int target_write_u16(struct target_s *target, uint32_t address, uint16_t value)
1580 uint8_t value_buf[2];
1581 if (!target_was_examined(target))
1583 LOG_ERROR("Target not examined yet");
1587 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1591 target_buffer_set_u16(target, value_buf, value);
1592 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1594 LOG_DEBUG("failed: %i", retval);
1600 int target_write_u8(struct target_s *target, uint32_t address, uint8_t value)
1603 if (!target_was_examined(target))
1605 LOG_ERROR("Target not examined yet");
1609 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1612 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1614 LOG_DEBUG("failed: %i", retval);
1620 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1622 target_t *target = all_targets;
1626 target = get_target(args[0]);
1627 if (target == NULL) {
1628 command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1631 if (!target->tap->enabled) {
1632 command_print(cmd_ctx,"Target: TAP %s is disabled, "
1633 "can't be the current target\n",
1634 target->tap->dotted_name);
1638 cmd_ctx->current_target = target->target_number;
1643 target = all_targets;
1644 command_print(cmd_ctx, " TargetName Type Endian TapName State ");
1645 command_print(cmd_ctx, "-- ------------------ ---------- ------ ------------------ ------------");
1651 if (target->tap->enabled)
1652 state = target_state_name( target );
1654 state = "tap-disabled";
1656 if (cmd_ctx->current_target == target->target_number)
1659 /* keep columns lined up to match the headers above */
1660 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1661 target->target_number,
1664 target_get_name(target),
1665 Jim_Nvp_value2name_simple(nvp_target_endian,
1666 target->endianness)->name,
1667 target->tap->dotted_name,
1669 target = target->next;
1675 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1677 static int powerDropout;
1678 static int srstAsserted;
1680 static int runPowerRestore;
1681 static int runPowerDropout;
1682 static int runSrstAsserted;
1683 static int runSrstDeasserted;
1685 static int sense_handler(void)
1687 static int prevSrstAsserted = 0;
1688 static int prevPowerdropout = 0;
1691 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1695 powerRestored = prevPowerdropout && !powerDropout;
1698 runPowerRestore = 1;
1701 long long current = timeval_ms();
1702 static long long lastPower = 0;
1703 int waitMore = lastPower + 2000 > current;
1704 if (powerDropout && !waitMore)
1706 runPowerDropout = 1;
1707 lastPower = current;
1710 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1714 srstDeasserted = prevSrstAsserted && !srstAsserted;
1716 static long long lastSrst = 0;
1717 waitMore = lastSrst + 2000 > current;
1718 if (srstDeasserted && !waitMore)
1720 runSrstDeasserted = 1;
1724 if (!prevSrstAsserted && srstAsserted)
1726 runSrstAsserted = 1;
1729 prevSrstAsserted = srstAsserted;
1730 prevPowerdropout = powerDropout;
1732 if (srstDeasserted || powerRestored)
1734 /* Other than logging the event we can't do anything here.
1735 * Issuing a reset is a particularly bad idea as we might
1736 * be inside a reset already.
1743 static void target_call_event_callbacks_all(enum target_event e) {
1745 target = all_targets;
1747 target_call_event_callbacks(target, e);
1748 target = target->next;
1752 /* process target state changes */
1753 int handle_target(void *priv)
1755 int retval = ERROR_OK;
1757 /* we do not want to recurse here... */
1758 static int recursive = 0;
1763 /* danger! running these procedures can trigger srst assertions and power dropouts.
1764 * We need to avoid an infinite loop/recursion here and we do that by
1765 * clearing the flags after running these events.
1767 int did_something = 0;
1768 if (runSrstAsserted)
1770 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1771 Jim_Eval(interp, "srst_asserted");
1774 if (runSrstDeasserted)
1776 Jim_Eval(interp, "srst_deasserted");
1779 if (runPowerDropout)
1781 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1782 Jim_Eval(interp, "power_dropout");
1785 if (runPowerRestore)
1787 Jim_Eval(interp, "power_restore");
1793 /* clear detect flags */
1797 /* clear action flags */
1799 runSrstAsserted = 0;
1800 runSrstDeasserted = 0;
1801 runPowerRestore = 0;
1802 runPowerDropout = 0;
1807 /* Poll targets for state changes unless that's globally disabled.
1808 * Skip targets that are currently disabled.
1810 for (target_t *target = all_targets;
1811 is_jtag_poll_safe() && target;
1812 target = target->next)
1814 if (!target->tap->enabled)
1817 /* only poll target if we've got power and srst isn't asserted */
1818 if (!powerDropout && !srstAsserted)
1820 /* polling may fail silently until the target has been examined */
1821 if ((retval = target_poll(target)) != ERROR_OK)
1823 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1832 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1841 target = get_current_target(cmd_ctx);
1843 /* list all available registers for the current target */
1846 reg_cache_t *cache = target->reg_cache;
1853 command_print(cmd_ctx, "===== %s", cache->name);
1855 for (i = 0, reg = cache->reg_list;
1856 i < cache->num_regs;
1857 i++, reg++, count++)
1859 /* only print cached values if they are valid */
1861 value = buf_to_str(reg->value,
1863 command_print(cmd_ctx,
1864 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1872 command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1877 cache = cache->next;
1883 /* access a single register by its ordinal number */
1884 if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1887 COMMAND_PARSE_NUMBER(uint, args[0], num);
1889 reg_cache_t *cache = target->reg_cache;
1894 for (i = 0; i < cache->num_regs; i++)
1896 if (count++ == (int)num)
1898 reg = &cache->reg_list[i];
1904 cache = cache->next;
1909 command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1912 } else /* access a single register by its name */
1914 reg = register_get_by_name(target->reg_cache, args[0], 1);
1918 command_print(cmd_ctx, "register %s not found in current target", args[0]);
1923 /* display a register */
1924 if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1926 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1929 if (reg->valid == 0)
1931 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1932 arch_type->get(reg);
1934 value = buf_to_str(reg->value, reg->size, 16);
1935 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1940 /* set register value */
1943 uint8_t *buf = malloc(CEIL(reg->size, 8));
1944 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1946 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1947 arch_type->set(reg, buf);
1949 value = buf_to_str(reg->value, reg->size, 16);
1950 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1958 command_print(cmd_ctx, "usage: reg <#|name> [value]");
1963 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1965 int retval = ERROR_OK;
1966 target_t *target = get_current_target(cmd_ctx);
1970 command_print(cmd_ctx, "background polling: %s",
1971 jtag_poll_get_enabled() ? "on" : "off");
1972 command_print(cmd_ctx, "TAP: %s (%s)",
1973 target->tap->dotted_name,
1974 target->tap->enabled ? "enabled" : "disabled");
1975 if (!target->tap->enabled)
1977 if ((retval = target_poll(target)) != ERROR_OK)
1979 if ((retval = target_arch_state(target)) != ERROR_OK)
1985 if (strcmp(args[0], "on") == 0)
1987 jtag_poll_set_enabled(true);
1989 else if (strcmp(args[0], "off") == 0)
1991 jtag_poll_set_enabled(false);
1995 command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1999 return ERROR_COMMAND_SYNTAX_ERROR;
2005 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2008 return ERROR_COMMAND_SYNTAX_ERROR;
2013 int retval = parse_uint(args[0], &ms);
2014 if (ERROR_OK != retval)
2016 command_print(cmd_ctx, "usage: %s [seconds]", cmd);
2017 return ERROR_COMMAND_SYNTAX_ERROR;
2019 // convert seconds (given) to milliseconds (needed)
2023 target_t *target = get_current_target(cmd_ctx);
2024 return target_wait_state(target, TARGET_HALTED, ms);
2027 /* wait for target state to change. The trick here is to have a low
2028 * latency for short waits and not to suck up all the CPU time
2031 * After 500ms, keep_alive() is invoked
2033 int target_wait_state(target_t *target, enum target_state state, int ms)
2036 long long then = 0, cur;
2041 if ((retval = target_poll(target)) != ERROR_OK)
2043 if (target->state == state)
2051 then = timeval_ms();
2052 LOG_DEBUG("waiting for target %s...",
2053 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2061 if ((cur-then) > ms)
2063 LOG_ERROR("timed out while waiting for target %s",
2064 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2072 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2076 target_t *target = get_current_target(cmd_ctx);
2077 int retval = target_halt(target);
2078 if (ERROR_OK != retval)
2084 retval = parse_uint(args[0], &wait);
2085 if (ERROR_OK != retval)
2086 return ERROR_COMMAND_SYNTAX_ERROR;
2091 return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
2094 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2096 target_t *target = get_current_target(cmd_ctx);
2098 LOG_USER("requesting target halt and executing a soft reset");
2100 target->type->soft_reset_halt(target);
2105 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2108 return ERROR_COMMAND_SYNTAX_ERROR;
2110 enum target_reset_mode reset_mode = RESET_RUN;
2114 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2115 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2116 return ERROR_COMMAND_SYNTAX_ERROR;
2118 reset_mode = n->value;
2121 /* reset *all* targets */
2122 return target_process_reset(cmd_ctx, reset_mode);
2126 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2130 return ERROR_COMMAND_SYNTAX_ERROR;
2132 target_t *target = get_current_target(cmd_ctx);
2133 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2135 /* with no args, resume from current pc, addr = 0,
2136 * with one arguments, addr = args[0],
2137 * handle breakpoints, not debugging */
2141 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2145 return target_resume(target, current, addr, 1, 0);
2148 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2151 return ERROR_COMMAND_SYNTAX_ERROR;
2155 /* with no args, step from current pc, addr = 0,
2156 * with one argument addr = args[0],
2157 * handle breakpoints, debugging */
2162 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2166 target_t *target = get_current_target(cmd_ctx);
2168 return target->type->step(target, current_pc, addr, 1);
2171 static void handle_md_output(struct command_context_s *cmd_ctx,
2172 struct target_s *target, uint32_t address, unsigned size,
2173 unsigned count, const uint8_t *buffer)
2175 const unsigned line_bytecnt = 32;
2176 unsigned line_modulo = line_bytecnt / size;
2178 char output[line_bytecnt * 4 + 1];
2179 unsigned output_len = 0;
2181 const char *value_fmt;
2183 case 4: value_fmt = "%8.8x "; break;
2184 case 2: value_fmt = "%4.2x "; break;
2185 case 1: value_fmt = "%2.2x "; break;
2187 LOG_ERROR("invalid memory read size: %u", size);
2191 for (unsigned i = 0; i < count; i++)
2193 if (i % line_modulo == 0)
2195 output_len += snprintf(output + output_len,
2196 sizeof(output) - output_len,
2198 (unsigned)(address + (i*size)));
2202 const uint8_t *value_ptr = buffer + i * size;
2204 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2205 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2206 case 1: value = *value_ptr;
2208 output_len += snprintf(output + output_len,
2209 sizeof(output) - output_len,
2212 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2214 command_print(cmd_ctx, "%s", output);
2220 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2223 return ERROR_COMMAND_SYNTAX_ERROR;
2227 case 'w': size = 4; break;
2228 case 'h': size = 2; break;
2229 case 'b': size = 1; break;
2230 default: return ERROR_COMMAND_SYNTAX_ERROR;
2233 bool physical=strcmp(args[0], "phys")==0;
2234 int (*fn)(struct target_s *target,
2235 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2240 fn=target_read_phys_memory;
2243 fn=target_read_memory;
2245 if ((argc < 1) || (argc > 2))
2247 return ERROR_COMMAND_SYNTAX_ERROR;
2251 COMMAND_PARSE_NUMBER(u32, args[0], address);
2255 COMMAND_PARSE_NUMBER(uint, args[1], count);
2257 uint8_t *buffer = calloc(count, size);
2259 target_t *target = get_current_target(cmd_ctx);
2260 int retval = fn(target, address, size, count, buffer);
2261 if (ERROR_OK == retval)
2262 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2269 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2273 return ERROR_COMMAND_SYNTAX_ERROR;
2275 bool physical=strcmp(args[0], "phys")==0;
2276 int (*fn)(struct target_s *target,
2277 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2282 fn=target_write_phys_memory;
2285 fn=target_write_memory;
2287 if ((argc < 2) || (argc > 3))
2288 return ERROR_COMMAND_SYNTAX_ERROR;
2291 COMMAND_PARSE_NUMBER(u32, args[0], address);
2294 COMMAND_PARSE_NUMBER(u32, args[1], value);
2298 COMMAND_PARSE_NUMBER(uint, args[2], count);
2300 target_t *target = get_current_target(cmd_ctx);
2302 uint8_t value_buf[4];
2307 target_buffer_set_u32(target, value_buf, value);
2311 target_buffer_set_u16(target, value_buf, value);
2315 value_buf[0] = value;
2318 return ERROR_COMMAND_SYNTAX_ERROR;
2320 for (unsigned i = 0; i < count; i++)
2322 int retval = fn(target,
2323 address + i * wordsize, wordsize, 1, value_buf);
2324 if (ERROR_OK != retval)
2333 static int parse_load_image_command_args(struct command_context_s *cmd_ctx,
2334 char **args, int argc, image_t *image,
2335 uint32_t *min_address, uint32_t *max_address)
2337 if (argc < 1 || argc > 5)
2338 return ERROR_COMMAND_SYNTAX_ERROR;
2340 /* a base address isn't always necessary,
2341 * default to 0x0 (i.e. don't relocate) */
2345 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2346 image->base_address = addr;
2347 image->base_address_set = 1;
2350 image->base_address_set = 0;
2352 image->start_address_set = 0;
2356 COMMAND_PARSE_NUMBER(u32, args[3], *min_address);
2360 COMMAND_PARSE_NUMBER(u32, args[4], *max_address);
2361 // use size (given) to find max (required)
2362 *max_address += *min_address;
2365 if (*min_address > *max_address)
2366 return ERROR_COMMAND_SYNTAX_ERROR;
2371 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2375 uint32_t image_size;
2376 uint32_t min_address = 0;
2377 uint32_t max_address = 0xffffffff;
2381 int retval = parse_load_image_command_args(cmd_ctx, args, argc,
2382 &image, &min_address, &max_address);
2383 if (ERROR_OK != retval)
2386 target_t *target = get_current_target(cmd_ctx);
2388 struct duration bench;
2389 duration_start(&bench);
2391 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2398 for (i = 0; i < image.num_sections; i++)
2400 buffer = malloc(image.sections[i].size);
2403 command_print(cmd_ctx,
2404 "error allocating buffer for section (%d bytes)",
2405 (int)(image.sections[i].size));
2409 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2415 uint32_t offset = 0;
2416 uint32_t length = buf_cnt;
2418 /* DANGER!!! beware of unsigned comparision here!!! */
2420 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2421 (image.sections[i].base_address < max_address))
2423 if (image.sections[i].base_address < min_address)
2425 /* clip addresses below */
2426 offset += min_address-image.sections[i].base_address;
2430 if (image.sections[i].base_address + buf_cnt > max_address)
2432 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2435 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2440 image_size += length;
2441 command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2442 (unsigned int)length,
2443 image.sections[i].base_address + offset);
2449 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2451 command_print(cmd_ctx, "downloaded %" PRIu32 " bytes "
2452 "in %fs (%0.3f kb/s)", image_size,
2453 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2456 image_close(&image);
2462 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2466 uint8_t buffer[560];
2470 target_t *target = get_current_target(cmd_ctx);
2474 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2479 COMMAND_PARSE_NUMBER(u32, args[1], address);
2481 COMMAND_PARSE_NUMBER(u32, args[2], size);
2483 if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2488 struct duration bench;
2489 duration_start(&bench);
2491 int retval = ERROR_OK;
2494 uint32_t size_written;
2495 uint32_t this_run_size = (size > 560) ? 560 : size;
2496 retval = target_read_buffer(target, address, this_run_size, buffer);
2497 if (retval != ERROR_OK)
2502 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2503 if (retval != ERROR_OK)
2508 size -= this_run_size;
2509 address += this_run_size;
2512 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2515 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2517 command_print(cmd_ctx,
2518 "dumped %lld bytes in %fs (%0.3f kb/s)", fileio.size,
2519 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2525 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2529 uint32_t image_size;
2532 uint32_t checksum = 0;
2533 uint32_t mem_checksum = 0;
2537 target_t *target = get_current_target(cmd_ctx);
2541 return ERROR_COMMAND_SYNTAX_ERROR;
2546 LOG_ERROR("no target selected");
2550 struct duration bench;
2551 duration_start(&bench);
2556 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2557 image.base_address = addr;
2558 image.base_address_set = 1;
2562 image.base_address_set = 0;
2563 image.base_address = 0x0;
2566 image.start_address_set = 0;
2568 if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2575 for (i = 0; i < image.num_sections; i++)
2577 buffer = malloc(image.sections[i].size);
2580 command_print(cmd_ctx,
2581 "error allocating buffer for section (%d bytes)",
2582 (int)(image.sections[i].size));
2585 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2593 /* calculate checksum of image */
2594 image_calculate_checksum(buffer, buf_cnt, &checksum);
2596 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2597 if (retval != ERROR_OK)
2603 if (checksum != mem_checksum)
2605 /* failed crc checksum, fall back to a binary compare */
2608 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2610 data = (uint8_t*)malloc(buf_cnt);
2612 /* Can we use 32bit word accesses? */
2614 int count = buf_cnt;
2615 if ((count % 4) == 0)
2620 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2621 if (retval == ERROR_OK)
2624 for (t = 0; t < buf_cnt; t++)
2626 if (data[t] != buffer[t])
2628 command_print(cmd_ctx,
2629 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2630 (unsigned)(t + image.sections[i].base_address),
2635 retval = ERROR_FAIL;
2649 command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2650 image.sections[i].base_address,
2655 image_size += buf_cnt;
2658 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2660 command_print(cmd_ctx, "verified %" PRIu32 " bytes "
2661 "in %fs (%0.3f kb/s)", image_size,
2662 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2665 image_close(&image);
2670 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2672 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2675 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2677 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2680 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2682 target_t *target = get_current_target(cmd_ctx);
2683 breakpoint_t *breakpoint = target->breakpoints;
2686 if (breakpoint->type == BKPT_SOFT)
2688 char* buf = buf_to_str(breakpoint->orig_instr,
2689 breakpoint->length, 16);
2690 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2691 breakpoint->address,
2693 breakpoint->set, buf);
2698 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2699 breakpoint->address,
2700 breakpoint->length, breakpoint->set);
2703 breakpoint = breakpoint->next;
2708 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2709 uint32_t addr, uint32_t length, int hw)
2711 target_t *target = get_current_target(cmd_ctx);
2712 int retval = breakpoint_add(target, addr, length, hw);
2713 if (ERROR_OK == retval)
2714 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2716 LOG_ERROR("Failure setting breakpoint");
2720 static int handle_bp_command(struct command_context_s *cmd_ctx,
2721 char *cmd, char **args, int argc)
2724 return handle_bp_command_list(cmd_ctx);
2726 if (argc < 2 || argc > 3)
2728 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2729 return ERROR_COMMAND_SYNTAX_ERROR;
2733 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2735 COMMAND_PARSE_NUMBER(u32, args[1], length);
2740 if (strcmp(args[2], "hw") == 0)
2743 return ERROR_COMMAND_SYNTAX_ERROR;
2746 return handle_bp_command_set(cmd_ctx, addr, length, hw);
2749 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2752 return ERROR_COMMAND_SYNTAX_ERROR;
2755 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2757 target_t *target = get_current_target(cmd_ctx);
2758 breakpoint_remove(target, addr);
2763 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2765 target_t *target = get_current_target(cmd_ctx);
2769 watchpoint_t *watchpoint = target->watchpoints;
2773 command_print(cmd_ctx,
2774 "address: 0x%8.8" PRIx32 ", len: 0x%8.8x, r/w/a: %i, value: 0x%8.8" PRIx32 ", mask: 0x%8.8" PRIx32 "",
2775 watchpoint->address,
2777 (int)(watchpoint->rw),
2780 watchpoint = watchpoint->next;
2785 enum watchpoint_rw type = WPT_ACCESS;
2787 uint32_t length = 0;
2788 uint32_t data_value = 0x0;
2789 uint32_t data_mask = 0xffffffff;
2794 COMMAND_PARSE_NUMBER(u32, args[4], data_mask);
2797 COMMAND_PARSE_NUMBER(u32, args[3], data_value);
2812 LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2813 return ERROR_COMMAND_SYNTAX_ERROR;
2817 COMMAND_PARSE_NUMBER(u32, args[1], length);
2818 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2822 command_print(cmd_ctx, "usage: wp [address length "
2823 "[(r|w|a) [value [mask]]]]");
2824 return ERROR_COMMAND_SYNTAX_ERROR;
2827 int retval = watchpoint_add(target, addr, length, type,
2828 data_value, data_mask);
2829 if (ERROR_OK != retval)
2830 LOG_ERROR("Failure setting watchpoints");
2835 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2838 return ERROR_COMMAND_SYNTAX_ERROR;
2841 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2843 target_t *target = get_current_target(cmd_ctx);
2844 watchpoint_remove(target, addr);
2851 * Translate a virtual address to a physical address.
2853 * The low-level target implementation must have logged a detailed error
2854 * which is forwarded to telnet/GDB session.
2856 static int handle_virt2phys_command(command_context_t *cmd_ctx,
2857 char *cmd, char **args, int argc)
2860 return ERROR_COMMAND_SYNTAX_ERROR;
2863 COMMAND_PARSE_NUMBER(u32, args[0], va);
2866 target_t *target = get_current_target(cmd_ctx);
2867 int retval = target->type->virt2phys(target, va, &pa);
2868 if (retval == ERROR_OK)
2869 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2874 static void writeData(FILE *f, const void *data, size_t len)
2876 size_t written = fwrite(data, 1, len, f);
2878 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2881 static void writeLong(FILE *f, int l)
2884 for (i = 0; i < 4; i++)
2886 char c = (l >> (i*8))&0xff;
2887 writeData(f, &c, 1);
2892 static void writeString(FILE *f, char *s)
2894 writeData(f, s, strlen(s));
2897 /* Dump a gmon.out histogram file. */
2898 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
2901 FILE *f = fopen(filename, "w");
2904 writeString(f, "gmon");
2905 writeLong(f, 0x00000001); /* Version */
2906 writeLong(f, 0); /* padding */
2907 writeLong(f, 0); /* padding */
2908 writeLong(f, 0); /* padding */
2910 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2911 writeData(f, &zero, 1);
2913 /* figure out bucket size */
2914 uint32_t min = samples[0];
2915 uint32_t max = samples[0];
2916 for (i = 0; i < sampleNum; i++)
2918 if (min > samples[i])
2922 if (max < samples[i])
2928 int addressSpace = (max-min + 1);
2930 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2931 uint32_t length = addressSpace;
2932 if (length > maxBuckets)
2934 length = maxBuckets;
2936 int *buckets = malloc(sizeof(int)*length);
2937 if (buckets == NULL)
2942 memset(buckets, 0, sizeof(int)*length);
2943 for (i = 0; i < sampleNum;i++)
2945 uint32_t address = samples[i];
2946 long long a = address-min;
2947 long long b = length-1;
2948 long long c = addressSpace-1;
2949 int index = (a*b)/c; /* danger!!!! int32 overflows */
2953 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2954 writeLong(f, min); /* low_pc */
2955 writeLong(f, max); /* high_pc */
2956 writeLong(f, length); /* # of samples */
2957 writeLong(f, 64000000); /* 64MHz */
2958 writeString(f, "seconds");
2959 for (i = 0; i < (15-strlen("seconds")); i++)
2960 writeData(f, &zero, 1);
2961 writeString(f, "s");
2963 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2965 char *data = malloc(2*length);
2968 for (i = 0; i < length;i++)
2977 data[i*2 + 1]=(val >> 8)&0xff;
2980 writeData(f, data, length * 2);
2990 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2991 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2993 target_t *target = get_current_target(cmd_ctx);
2994 struct timeval timeout, now;
2996 gettimeofday(&timeout, NULL);
2999 return ERROR_COMMAND_SYNTAX_ERROR;
3002 COMMAND_PARSE_NUMBER(uint, args[0], offset);
3004 timeval_add_time(&timeout, offset, 0);
3006 command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3008 static const int maxSample = 10000;
3009 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3010 if (samples == NULL)
3014 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3015 reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
3020 target_poll(target);
3021 if (target->state == TARGET_HALTED)
3023 uint32_t t=*((uint32_t *)reg->value);
3024 samples[numSamples++]=t;
3025 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3026 target_poll(target);
3027 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3028 } else if (target->state == TARGET_RUNNING)
3030 /* We want to quickly sample the PC. */
3031 if ((retval = target_halt(target)) != ERROR_OK)
3038 command_print(cmd_ctx, "Target not halted or running");
3042 if (retval != ERROR_OK)
3047 gettimeofday(&now, NULL);
3048 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3050 command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3051 if ((retval = target_poll(target)) != ERROR_OK)
3056 if (target->state == TARGET_HALTED)
3058 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3060 if ((retval = target_poll(target)) != ERROR_OK)
3065 writeGmon(samples, numSamples, args[1]);
3066 command_print(cmd_ctx, "Wrote %s", args[1]);
3075 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3078 Jim_Obj *nameObjPtr, *valObjPtr;
3081 namebuf = alloc_printf("%s(%d)", varname, idx);
3085 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3086 valObjPtr = Jim_NewIntObj(interp, val);
3087 if (!nameObjPtr || !valObjPtr)
3093 Jim_IncrRefCount(nameObjPtr);
3094 Jim_IncrRefCount(valObjPtr);
3095 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3096 Jim_DecrRefCount(interp, nameObjPtr);
3097 Jim_DecrRefCount(interp, valObjPtr);
3099 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3103 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3105 command_context_t *context;
3108 context = Jim_GetAssocData(interp, "context");
3109 if (context == NULL)
3111 LOG_ERROR("mem2array: no command context");
3114 target = get_current_target(context);
3117 LOG_ERROR("mem2array: no current target");
3121 return target_mem2array(interp, target, argc-1, argv + 1);
3124 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3132 const char *varname;
3133 uint8_t buffer[4096];
3137 /* argv[1] = name of array to receive the data
3138 * argv[2] = desired width
3139 * argv[3] = memory address
3140 * argv[4] = count of times to read
3143 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3146 varname = Jim_GetString(argv[0], &len);
3147 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3149 e = Jim_GetLong(interp, argv[1], &l);
3155 e = Jim_GetLong(interp, argv[2], &l);
3160 e = Jim_GetLong(interp, argv[3], &l);
3176 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3177 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3181 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3182 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3185 if ((addr + (len * width)) < addr) {
3186 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3187 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3190 /* absurd transfer size? */
3192 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3193 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3198 ((width == 2) && ((addr & 1) == 0)) ||
3199 ((width == 4) && ((addr & 3) == 0))) {
3203 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3204 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3207 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3218 /* Slurp... in buffer size chunks */
3220 count = len; /* in objects.. */
3221 if (count > (sizeof(buffer)/width)) {
3222 count = (sizeof(buffer)/width);
3225 retval = target_read_memory(target, addr, width, count, buffer);
3226 if (retval != ERROR_OK) {
3228 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3232 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3233 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3237 v = 0; /* shut up gcc */
3238 for (i = 0 ;i < count ;i++, n++) {
3241 v = target_buffer_get_u32(target, &buffer[i*width]);
3244 v = target_buffer_get_u16(target, &buffer[i*width]);
3247 v = buffer[i] & 0x0ff;
3250 new_int_array_element(interp, varname, n, v);
3256 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3261 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3264 Jim_Obj *nameObjPtr, *valObjPtr;
3268 namebuf = alloc_printf("%s(%d)", varname, idx);
3272 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3279 Jim_IncrRefCount(nameObjPtr);
3280 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3281 Jim_DecrRefCount(interp, nameObjPtr);
3283 if (valObjPtr == NULL)
3286 result = Jim_GetLong(interp, valObjPtr, &l);
3287 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3292 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3294 command_context_t *context;
3297 context = Jim_GetAssocData(interp, "context");
3298 if (context == NULL) {
3299 LOG_ERROR("array2mem: no command context");
3302 target = get_current_target(context);
3303 if (target == NULL) {
3304 LOG_ERROR("array2mem: no current target");
3308 return target_array2mem(interp,target, argc-1, argv + 1);
3310 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3318 const char *varname;
3319 uint8_t buffer[4096];
3323 /* argv[1] = name of array to get the data
3324 * argv[2] = desired width
3325 * argv[3] = memory address
3326 * argv[4] = count to write
3329 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3332 varname = Jim_GetString(argv[0], &len);
3333 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3335 e = Jim_GetLong(interp, argv[1], &l);
3341 e = Jim_GetLong(interp, argv[2], &l);
3346 e = Jim_GetLong(interp, argv[3], &l);
3362 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3363 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3367 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3368 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3371 if ((addr + (len * width)) < addr) {
3372 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3373 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3376 /* absurd transfer size? */
3378 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3379 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3384 ((width == 2) && ((addr & 1) == 0)) ||
3385 ((width == 4) && ((addr & 3) == 0))) {
3389 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3390 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3393 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3404 /* Slurp... in buffer size chunks */
3406 count = len; /* in objects.. */
3407 if (count > (sizeof(buffer)/width)) {
3408 count = (sizeof(buffer)/width);
3411 v = 0; /* shut up gcc */
3412 for (i = 0 ;i < count ;i++, n++) {
3413 get_int_array_element(interp, varname, n, &v);
3416 target_buffer_set_u32(target, &buffer[i*width], v);
3419 target_buffer_set_u16(target, &buffer[i*width], v);
3422 buffer[i] = v & 0x0ff;
3428 retval = target_write_memory(target, addr, width, count, buffer);
3429 if (retval != ERROR_OK) {
3431 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3435 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3436 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3442 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3447 void target_all_handle_event(enum target_event e)
3451 LOG_DEBUG("**all*targets: event: %d, %s",
3453 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3455 target = all_targets;
3457 target_handle_event(target, e);
3458 target = target->next;
3463 /* FIX? should we propagate errors here rather than printing them
3466 void target_handle_event(target_t *target, enum target_event e)
3468 target_event_action_t *teap;
3470 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3471 if (teap->event == e) {
3472 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3473 target->target_number,
3475 target_get_name(target),
3477 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3478 Jim_GetString(teap->body, NULL));
3479 if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3481 Jim_PrintErrorMessage(interp);
3487 enum target_cfg_param {
3490 TCFG_WORK_AREA_VIRT,
3491 TCFG_WORK_AREA_PHYS,
3492 TCFG_WORK_AREA_SIZE,
3493 TCFG_WORK_AREA_BACKUP,
3496 TCFG_CHAIN_POSITION,
3499 static Jim_Nvp nvp_config_opts[] = {
3500 { .name = "-type", .value = TCFG_TYPE },
3501 { .name = "-event", .value = TCFG_EVENT },
3502 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3503 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3504 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3505 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3506 { .name = "-endian" , .value = TCFG_ENDIAN },
3507 { .name = "-variant", .value = TCFG_VARIANT },
3508 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3510 { .name = NULL, .value = -1 }
3513 static int target_configure(Jim_GetOptInfo *goi, target_t *target)
3521 /* parse config or cget options ... */
3522 while (goi->argc > 0) {
3523 Jim_SetEmptyResult(goi->interp);
3524 /* Jim_GetOpt_Debug(goi); */
3526 if (target->type->target_jim_configure) {
3527 /* target defines a configure function */
3528 /* target gets first dibs on parameters */
3529 e = (*(target->type->target_jim_configure))(target, goi);
3538 /* otherwise we 'continue' below */
3540 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3542 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3548 if (goi->isconfigure) {
3549 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3553 if (goi->argc != 0) {
3554 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3558 Jim_SetResultString(goi->interp, target_get_name(target), -1);
3562 if (goi->argc == 0) {
3563 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3567 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3569 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3573 if (goi->isconfigure) {
3574 if (goi->argc != 1) {
3575 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3579 if (goi->argc != 0) {
3580 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3586 target_event_action_t *teap;
3588 teap = target->event_action;
3589 /* replace existing? */
3591 if (teap->event == (enum target_event)n->value) {
3597 if (goi->isconfigure) {
3598 bool replace = true;
3601 teap = calloc(1, sizeof(*teap));
3604 teap->event = n->value;
3605 Jim_GetOpt_Obj(goi, &o);
3607 Jim_DecrRefCount(interp, teap->body);
3609 teap->body = Jim_DuplicateObj(goi->interp, o);
3612 * Tcl/TK - "tk events" have a nice feature.
3613 * See the "BIND" command.
3614 * We should support that here.
3615 * You can specify %X and %Y in the event code.
3616 * The idea is: %T - target name.
3617 * The idea is: %N - target number
3618 * The idea is: %E - event name.
3620 Jim_IncrRefCount(teap->body);
3624 /* add to head of event list */
3625 teap->next = target->event_action;
3626 target->event_action = teap;
3628 Jim_SetEmptyResult(goi->interp);
3632 Jim_SetEmptyResult(goi->interp);
3634 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3641 case TCFG_WORK_AREA_VIRT:
3642 if (goi->isconfigure) {
3643 target_free_all_working_areas(target);
3644 e = Jim_GetOpt_Wide(goi, &w);
3648 target->working_area_virt = w;
3649 target->working_area_virt_spec = true;
3651 if (goi->argc != 0) {
3655 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3659 case TCFG_WORK_AREA_PHYS:
3660 if (goi->isconfigure) {
3661 target_free_all_working_areas(target);
3662 e = Jim_GetOpt_Wide(goi, &w);
3666 target->working_area_phys = w;
3667 target->working_area_phys_spec = true;
3669 if (goi->argc != 0) {
3673 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3677 case TCFG_WORK_AREA_SIZE:
3678 if (goi->isconfigure) {
3679 target_free_all_working_areas(target);
3680 e = Jim_GetOpt_Wide(goi, &w);
3684 target->working_area_size = w;
3686 if (goi->argc != 0) {
3690 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3694 case TCFG_WORK_AREA_BACKUP:
3695 if (goi->isconfigure) {
3696 target_free_all_working_areas(target);
3697 e = Jim_GetOpt_Wide(goi, &w);
3701 /* make this exactly 1 or 0 */
3702 target->backup_working_area = (!!w);
3704 if (goi->argc != 0) {
3708 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3709 /* loop for more e*/
3713 if (goi->isconfigure) {
3714 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3716 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3719 target->endianness = n->value;
3721 if (goi->argc != 0) {
3725 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3726 if (n->name == NULL) {
3727 target->endianness = TARGET_LITTLE_ENDIAN;
3728 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3730 Jim_SetResultString(goi->interp, n->name, -1);
3735 if (goi->isconfigure) {
3736 if (goi->argc < 1) {
3737 Jim_SetResult_sprintf(goi->interp,
3742 if (target->variant) {
3743 free((void *)(target->variant));
3745 e = Jim_GetOpt_String(goi, &cp, NULL);
3746 target->variant = strdup(cp);
3748 if (goi->argc != 0) {
3752 Jim_SetResultString(goi->interp, target->variant,-1);
3755 case TCFG_CHAIN_POSITION:
3756 if (goi->isconfigure) {
3759 target_free_all_working_areas(target);
3760 e = Jim_GetOpt_Obj(goi, &o);
3764 tap = jtag_tap_by_jim_obj(goi->interp, o);
3768 /* make this exactly 1 or 0 */
3771 if (goi->argc != 0) {
3775 Jim_SetResultString(interp, target->tap->dotted_name, -1);
3776 /* loop for more e*/
3779 } /* while (goi->argc) */
3782 /* done - we return */
3786 /** this is the 'tcl' handler for the target specific command */
3787 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3792 uint8_t target_buf[32];
3795 struct command_context_s *cmd_ctx;
3802 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3803 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3804 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3805 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3813 TS_CMD_INVOKE_EVENT,
3816 static const Jim_Nvp target_options[] = {
3817 { .name = "configure", .value = TS_CMD_CONFIGURE },
3818 { .name = "cget", .value = TS_CMD_CGET },
3819 { .name = "mww", .value = TS_CMD_MWW },
3820 { .name = "mwh", .value = TS_CMD_MWH },
3821 { .name = "mwb", .value = TS_CMD_MWB },
3822 { .name = "mdw", .value = TS_CMD_MDW },
3823 { .name = "mdh", .value = TS_CMD_MDH },
3824 { .name = "mdb", .value = TS_CMD_MDB },
3825 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3826 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3827 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3828 { .name = "curstate", .value = TS_CMD_CURSTATE },
3830 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3831 { .name = "arp_poll", .value = TS_CMD_POLL },
3832 { .name = "arp_reset", .value = TS_CMD_RESET },
3833 { .name = "arp_halt", .value = TS_CMD_HALT },
3834 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3835 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3837 { .name = NULL, .value = -1 },
3840 /* go past the "command" */
3841 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3843 target = Jim_CmdPrivData(goi.interp);
3844 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3846 /* commands here are in an NVP table */
3847 e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3849 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3852 /* Assume blank result */
3853 Jim_SetEmptyResult(goi.interp);
3856 case TS_CMD_CONFIGURE:
3858 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3861 goi.isconfigure = 1;
3862 return target_configure(&goi, target);
3864 // some things take params
3866 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3869 goi.isconfigure = 0;
3870 return target_configure(&goi, target);
3878 * argv[3] = optional count.
3881 if ((goi.argc == 2) || (goi.argc == 3)) {
3885 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3889 e = Jim_GetOpt_Wide(&goi, &a);
3894 e = Jim_GetOpt_Wide(&goi, &b);
3898 if (goi.argc == 3) {
3899 e = Jim_GetOpt_Wide(&goi, &c);
3909 target_buffer_set_u32(target, target_buf, b);
3913 target_buffer_set_u16(target, target_buf, b);
3917 target_buffer_set_u8(target, target_buf, b);
3921 for (x = 0 ; x < c ; x++) {
3922 e = target_write_memory(target, a, b, 1, target_buf);
3923 if (e != ERROR_OK) {
3924 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3937 /* argv[0] = command
3939 * argv[2] = optional count
3941 if ((goi.argc == 2) || (goi.argc == 3)) {
3942 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3945 e = Jim_GetOpt_Wide(&goi, &a);
3950 e = Jim_GetOpt_Wide(&goi, &c);
3957 b = 1; /* shut up gcc */
3970 /* convert to "bytes" */
3972 /* count is now in 'BYTES' */
3978 e = target_read_memory(target, a, b, y / b, target_buf);
3979 if (e != ERROR_OK) {
3980 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
3984 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
3987 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
3988 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
3989 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
3991 for (; (x < 16) ; x += 4) {
3992 Jim_fprintf(interp, interp->cookie_stdout, " ");
3996 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
3997 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
3998 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4000 for (; (x < 16) ; x += 2) {
4001 Jim_fprintf(interp, interp->cookie_stdout, " ");
4006 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4007 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4008 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4010 for (; (x < 16) ; x += 1) {
4011 Jim_fprintf(interp, interp->cookie_stdout, " ");
4015 /* ascii-ify the bytes */
4016 for (x = 0 ; x < y ; x++) {
4017 if ((target_buf[x] >= 0x20) &&
4018 (target_buf[x] <= 0x7e)) {
4022 target_buf[x] = '.';
4027 target_buf[x] = ' ';
4032 /* print - with a newline */
4033 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4039 case TS_CMD_MEM2ARRAY:
4040 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4042 case TS_CMD_ARRAY2MEM:
4043 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4045 case TS_CMD_EXAMINE:
4047 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4050 if (!target->tap->enabled)
4051 goto err_tap_disabled;
4052 e = target->type->examine(target);
4053 if (e != ERROR_OK) {
4054 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4060 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4063 if (!target->tap->enabled)
4064 goto err_tap_disabled;
4065 if (!(target_was_examined(target))) {
4066 e = ERROR_TARGET_NOT_EXAMINED;
4068 e = target->type->poll(target);
4070 if (e != ERROR_OK) {
4071 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4078 if (goi.argc != 2) {
4079 Jim_WrongNumArgs(interp, 2, argv,
4080 "([tT]|[fF]|assert|deassert) BOOL");
4083 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4085 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4088 /* the halt or not param */
4089 e = Jim_GetOpt_Wide(&goi, &a);
4093 if (!target->tap->enabled)
4094 goto err_tap_disabled;
4095 if (!target->type->assert_reset
4096 || !target->type->deassert_reset) {
4097 Jim_SetResult_sprintf(interp,
4098 "No target-specific reset for %s",
4102 /* determine if we should halt or not. */
4103 target->reset_halt = !!a;
4104 /* When this happens - all workareas are invalid. */
4105 target_free_all_working_areas_restore(target, 0);
4108 if (n->value == NVP_ASSERT) {
4109 e = target->type->assert_reset(target);
4111 e = target->type->deassert_reset(target);
4113 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4116 Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4119 if (!target->tap->enabled)
4120 goto err_tap_disabled;
4121 e = target->type->halt(target);
4122 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4123 case TS_CMD_WAITSTATE:
4124 /* params: <name> statename timeoutmsecs */
4125 if (goi.argc != 2) {
4126 Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4129 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4131 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4134 e = Jim_GetOpt_Wide(&goi, &a);
4138 if (!target->tap->enabled)
4139 goto err_tap_disabled;
4140 e = target_wait_state(target, n->value, a);
4141 if (e != ERROR_OK) {
4142 Jim_SetResult_sprintf(goi.interp,
4143 "target: %s wait %s fails (%d) %s",
4146 e, target_strerror_safe(e));
4151 case TS_CMD_EVENTLIST:
4152 /* List for human, Events defined for this target.
4153 * scripts/programs should use 'name cget -event NAME'
4156 target_event_action_t *teap;
4157 teap = target->event_action;
4158 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4159 target->target_number,
4161 command_print(cmd_ctx, "%-25s | Body", "Event");
4162 command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4164 command_print(cmd_ctx,
4166 Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4167 Jim_GetString(teap->body, NULL));
4170 command_print(cmd_ctx, "***END***");
4173 case TS_CMD_CURSTATE:
4174 if (goi.argc != 0) {
4175 Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4178 Jim_SetResultString(goi.interp,
4179 target_state_name( target ),
4182 case TS_CMD_INVOKE_EVENT:
4183 if (goi.argc != 1) {
4184 Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4187 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4189 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4192 target_handle_event(target, n->value);
4198 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4202 static int target_create(Jim_GetOptInfo *goi)
4211 struct command_context_s *cmd_ctx;
4213 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4214 if (goi->argc < 3) {
4215 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4220 Jim_GetOpt_Obj(goi, &new_cmd);
4221 /* does this command exist? */
4222 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4224 cp = Jim_GetString(new_cmd, NULL);
4225 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4230 e = Jim_GetOpt_String(goi, &cp2, NULL);
4232 /* now does target type exist */
4233 for (x = 0 ; target_types[x] ; x++) {
4234 if (0 == strcmp(cp, target_types[x]->name)) {
4239 if (target_types[x] == NULL) {
4240 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4241 for (x = 0 ; target_types[x] ; x++) {
4242 if (target_types[x + 1]) {
4243 Jim_AppendStrings(goi->interp,
4244 Jim_GetResult(goi->interp),
4245 target_types[x]->name,
4248 Jim_AppendStrings(goi->interp,
4249 Jim_GetResult(goi->interp),
4251 target_types[x]->name,NULL);
4258 target = calloc(1,sizeof(target_t));
4259 /* set target number */
4260 target->target_number = new_target_number();
4262 /* allocate memory for each unique target type */
4263 target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4265 memcpy(target->type, target_types[x], sizeof(target_type_t));
4267 /* will be set by "-endian" */
4268 target->endianness = TARGET_ENDIAN_UNKNOWN;
4270 target->working_area = 0x0;
4271 target->working_area_size = 0x0;
4272 target->working_areas = NULL;
4273 target->backup_working_area = 0;
4275 target->state = TARGET_UNKNOWN;
4276 target->debug_reason = DBG_REASON_UNDEFINED;
4277 target->reg_cache = NULL;
4278 target->breakpoints = NULL;
4279 target->watchpoints = NULL;
4280 target->next = NULL;
4281 target->arch_info = NULL;
4283 target->display = 1;
4285 target->halt_issued = false;
4287 /* initialize trace information */
4288 target->trace_info = malloc(sizeof(trace_t));
4289 target->trace_info->num_trace_points = 0;
4290 target->trace_info->trace_points_size = 0;
4291 target->trace_info->trace_points = NULL;
4292 target->trace_info->trace_history_size = 0;
4293 target->trace_info->trace_history = NULL;
4294 target->trace_info->trace_history_pos = 0;
4295 target->trace_info->trace_history_overflowed = 0;
4297 target->dbgmsg = NULL;
4298 target->dbg_msg_enabled = 0;
4300 target->endianness = TARGET_ENDIAN_UNKNOWN;
4302 /* Do the rest as "configure" options */
4303 goi->isconfigure = 1;
4304 e = target_configure(goi, target);
4306 if (target->tap == NULL)
4308 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4318 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4319 /* default endian to little if not specified */
4320 target->endianness = TARGET_LITTLE_ENDIAN;
4323 /* incase variant is not set */
4324 if (!target->variant)
4325 target->variant = strdup("");
4327 /* create the target specific commands */
4328 if (target->type->register_commands) {
4329 (*(target->type->register_commands))(cmd_ctx);
4331 if (target->type->target_create) {
4332 (*(target->type->target_create))(target, goi->interp);
4335 /* append to end of list */
4338 tpp = &(all_targets);
4340 tpp = &((*tpp)->next);
4345 cp = Jim_GetString(new_cmd, NULL);
4346 target->cmd_name = strdup(cp);
4348 /* now - create the new target name command */
4349 e = Jim_CreateCommand(goi->interp,
4352 tcl_target_func, /* C function */
4353 target, /* private data */
4354 NULL); /* no del proc */
4359 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4363 struct command_context_s *cmd_ctx;
4367 /* TG = target generic */
4375 const char *target_cmds[] = {
4376 "create", "types", "names", "current", "number",
4378 NULL /* terminate */
4381 LOG_DEBUG("Target command params:");
4382 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4384 cmd_ctx = Jim_GetAssocData(interp, "context");
4386 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4388 if (goi.argc == 0) {
4389 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4393 /* Jim_GetOpt_Debug(&goi); */
4394 r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4401 Jim_Panic(goi.interp,"Why am I here?");
4403 case TG_CMD_CURRENT:
4404 if (goi.argc != 0) {
4405 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4408 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4411 if (goi.argc != 0) {
4412 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4415 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4416 for (x = 0 ; target_types[x] ; x++) {
4417 Jim_ListAppendElement(goi.interp,
4418 Jim_GetResult(goi.interp),
4419 Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4423 if (goi.argc != 0) {
4424 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4427 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4428 target = all_targets;
4430 Jim_ListAppendElement(goi.interp,
4431 Jim_GetResult(goi.interp),
4432 Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4433 target = target->next;
4438 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4441 return target_create(&goi);
4444 /* It's OK to remove this mechanism sometime after August 2010 or so */
4445 LOG_WARNING("don't use numbers as target identifiers; use names");
4446 if (goi.argc != 1) {
4447 Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4450 e = Jim_GetOpt_Wide(&goi, &w);
4454 for (x = 0, target = all_targets; target; target = target->next, x++) {
4455 if (target->target_number == w)
4458 if (target == NULL) {
4459 Jim_SetResult_sprintf(goi.interp,
4460 "Target: number %d does not exist", (int)(w));
4463 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4466 if (goi.argc != 0) {
4467 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4470 for (x = 0, target = all_targets; target; target = target->next, x++)
4472 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4488 static int fastload_num;
4489 static struct FastLoad *fastload;
4491 static void free_fastload(void)
4493 if (fastload != NULL)
4496 for (i = 0; i < fastload_num; i++)
4498 if (fastload[i].data)
4499 free(fastload[i].data);
4509 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4513 uint32_t image_size;
4514 uint32_t min_address = 0;
4515 uint32_t max_address = 0xffffffff;
4520 int retval = parse_load_image_command_args(cmd_ctx, args, argc,
4521 &image, &min_address, &max_address);
4522 if (ERROR_OK != retval)
4525 struct duration bench;
4526 duration_start(&bench);
4528 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4535 fastload_num = image.num_sections;
4536 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4537 if (fastload == NULL)
4539 image_close(&image);
4542 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4543 for (i = 0; i < image.num_sections; i++)
4545 buffer = malloc(image.sections[i].size);
4548 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4549 (int)(image.sections[i].size));
4553 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4559 uint32_t offset = 0;
4560 uint32_t length = buf_cnt;
4563 /* DANGER!!! beware of unsigned comparision here!!! */
4565 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4566 (image.sections[i].base_address < max_address))
4568 if (image.sections[i].base_address < min_address)
4570 /* clip addresses below */
4571 offset += min_address-image.sections[i].base_address;
4575 if (image.sections[i].base_address + buf_cnt > max_address)
4577 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4580 fastload[i].address = image.sections[i].base_address + offset;
4581 fastload[i].data = malloc(length);
4582 if (fastload[i].data == NULL)
4587 memcpy(fastload[i].data, buffer + offset, length);
4588 fastload[i].length = length;
4590 image_size += length;
4591 command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4592 (unsigned int)length,
4593 ((unsigned int)(image.sections[i].base_address + offset)));
4599 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4601 command_print(cmd_ctx, "Loaded %" PRIu32 " bytes "
4602 "in %fs (%0.3f kb/s)", image_size,
4603 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4605 command_print(cmd_ctx,
4606 "WARNING: image has not been loaded to target!"
4607 "You can issue a 'fast_load' to finish loading.");
4610 image_close(&image);
4612 if (retval != ERROR_OK)
4620 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4623 return ERROR_COMMAND_SYNTAX_ERROR;
4624 if (fastload == NULL)
4626 LOG_ERROR("No image in memory");
4630 int ms = timeval_ms();
4632 int retval = ERROR_OK;
4633 for (i = 0; i < fastload_num;i++)
4635 target_t *target = get_current_target(cmd_ctx);
4636 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4637 (unsigned int)(fastload[i].address),
4638 (unsigned int)(fastload[i].length));
4639 if (retval == ERROR_OK)
4641 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4643 size += fastload[i].length;
4645 int after = timeval_ms();
4646 command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4650 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4652 command_context_t *context;
4656 context = Jim_GetAssocData(interp, "context");
4657 if (context == NULL) {
4658 LOG_ERROR("array2mem: no command context");
4661 target = get_current_target(context);
4662 if (target == NULL) {
4663 LOG_ERROR("array2mem: no current target");
4667 if ((argc < 6) || (argc > 7))
4681 e = Jim_GetLong(interp, argv[1], &l);
4687 e = Jim_GetLong(interp, argv[2], &l);
4693 e = Jim_GetLong(interp, argv[3], &l);
4699 e = Jim_GetLong(interp, argv[4], &l);
4705 e = Jim_GetLong(interp, argv[5], &l);
4715 e = Jim_GetLong(interp, argv[6], &l);
4721 retval = target_mcr(target, cpnum, op1, op2, CRn, CRm, value);
4722 if (retval != ERROR_OK)
4726 retval = target_mrc(target, cpnum, op1, op2, CRn, CRm, &value);
4727 if (retval != ERROR_OK)
4730 Jim_SetResult(interp, Jim_NewIntObj(interp, value));
4736 int target_register_commands(struct command_context_s *cmd_ctx)
4739 register_command(cmd_ctx, NULL, "targets",
4740 handle_targets_command, COMMAND_EXEC,
4741 "change current command line target (one parameter) "
4742 "or list targets (no parameters)");
4744 register_jim(cmd_ctx, "target", jim_target, "configure target");
4749 int target_register_user_commands(struct command_context_s *cmd_ctx)
4751 int retval = ERROR_OK;
4752 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
4755 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
4758 register_command(cmd_ctx, NULL, "profile",
4759 handle_profile_command, COMMAND_EXEC,
4760 "profiling samples the CPU PC");
4762 register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array,
4763 "read memory and return as a TCL array for script processing "
4764 "<ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
4766 register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem,
4767 "convert a TCL array to memory locations and write the values "
4768 "<ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
4770 register_command(cmd_ctx, NULL, "fast_load_image",
4771 handle_fast_load_image_command, COMMAND_ANY,
4772 "same args as load_image, image stored in memory "
4773 "- mainly for profiling purposes");
4775 register_command(cmd_ctx, NULL, "fast_load",
4776 handle_fast_load_command, COMMAND_ANY,
4777 "loads active fast load image to current target "
4778 "- mainly for profiling purposes");
4781 register_command(cmd_ctx, NULL, "virt2phys",
4782 handle_virt2phys_command, COMMAND_ANY,
4783 "translate a virtual address into a physical address");
4784 register_command(cmd_ctx, NULL, "reg",
4785 handle_reg_command, COMMAND_EXEC,
4786 "display or set a register");
4788 register_command(cmd_ctx, NULL, "poll",
4789 handle_poll_command, COMMAND_EXEC,
4790 "poll target state");
4791 register_command(cmd_ctx, NULL, "wait_halt",
4792 handle_wait_halt_command, COMMAND_EXEC,
4793 "wait for target halt [time (s)]");
4794 register_command(cmd_ctx, NULL, "halt",
4795 handle_halt_command, COMMAND_EXEC,
4797 register_command(cmd_ctx, NULL, "resume",
4798 handle_resume_command, COMMAND_EXEC,
4799 "resume target [addr]");
4800 register_command(cmd_ctx, NULL, "reset",
4801 handle_reset_command, COMMAND_EXEC,
4802 "reset target [run | halt | init] - default is run");
4803 register_command(cmd_ctx, NULL, "soft_reset_halt",
4804 handle_soft_reset_halt_command, COMMAND_EXEC,
4805 "halt the target and do a soft reset");
4807 register_command(cmd_ctx, NULL, "step",
4808 handle_step_command, COMMAND_EXEC,
4809 "step one instruction from current PC or [addr]");
4811 register_command(cmd_ctx, NULL, "mdw",
4812 handle_md_command, COMMAND_EXEC,
4813 "display memory words [phys] <addr> [count]");
4814 register_command(cmd_ctx, NULL, "mdh",
4815 handle_md_command, COMMAND_EXEC,
4816 "display memory half-words [phys] <addr> [count]");
4817 register_command(cmd_ctx, NULL, "mdb",
4818 handle_md_command, COMMAND_EXEC,
4819 "display memory bytes [phys] <addr> [count]");
4821 register_command(cmd_ctx, NULL, "mww",
4822 handle_mw_command, COMMAND_EXEC,
4823 "write memory word [phys] <addr> <value> [count]");
4824 register_command(cmd_ctx, NULL, "mwh",
4825 handle_mw_command, COMMAND_EXEC,
4826 "write memory half-word [phys] <addr> <value> [count]");
4827 register_command(cmd_ctx, NULL, "mwb",
4828 handle_mw_command, COMMAND_EXEC,
4829 "write memory byte [phys] <addr> <value> [count]");
4831 register_command(cmd_ctx, NULL, "bp",
4832 handle_bp_command, COMMAND_EXEC,
4833 "list or set breakpoint [<address> <length> [hw]]");
4834 register_command(cmd_ctx, NULL, "rbp",
4835 handle_rbp_command, COMMAND_EXEC,
4836 "remove breakpoint <address>");
4838 register_command(cmd_ctx, NULL, "wp",
4839 handle_wp_command, COMMAND_EXEC,
4840 "list or set watchpoint "
4841 "[<address> <length> <r/w/a> [value] [mask]]");
4842 register_command(cmd_ctx, NULL, "rwp",
4843 handle_rwp_command, COMMAND_EXEC,
4844 "remove watchpoint <address>");
4846 register_command(cmd_ctx, NULL, "load_image",
4847 handle_load_image_command, COMMAND_EXEC,
4848 "load_image <file> <address> "
4849 "['bin'|'ihex'|'elf'|'s19'] [min_address] [max_length]");
4850 register_command(cmd_ctx, NULL, "dump_image",
4851 handle_dump_image_command, COMMAND_EXEC,
4852 "dump_image <file> <address> <size>");
4853 register_command(cmd_ctx, NULL, "verify_image",
4854 handle_verify_image_command, COMMAND_EXEC,
4855 "verify_image <file> [offset] [type]");
4856 register_command(cmd_ctx, NULL, "test_image",
4857 handle_test_image_command, COMMAND_EXEC,
4858 "test_image <file> [offset] [type]");