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: %s", __func__);
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: %s", __func__);
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);
741 default_read_phys_memory(struct target_s *target, uint32_t address,
742 uint32_t size, uint32_t count, uint8_t *buffer)
744 LOG_ERROR("Not implemented: %s", __func__);
749 default_write_phys_memory(struct target_s *target, uint32_t address,
750 uint32_t size, uint32_t count, uint8_t *buffer)
752 LOG_ERROR("Not implemented: %s", __func__);
756 int target_init(struct command_context_s *cmd_ctx)
758 target_t *target = all_targets;
763 target_reset_examined(target);
764 if (target->type->examine == NULL)
766 target->type->examine = default_examine;
769 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
771 LOG_ERROR("target '%s' init failed", target_get_name(target));
775 /* Set up default functions if none are provided by target */
776 if (target->type->virt2phys == NULL)
778 target->type->virt2phys = default_virt2phys;
781 if (target->type->read_phys_memory == NULL)
783 target->type->read_phys_memory = default_read_phys_memory;
786 if (target->type->write_phys_memory == NULL)
788 target->type->write_phys_memory = default_write_phys_memory;
791 if (target->type->mcr == NULL)
793 target->type->mcr = default_mcr;
796 /* FIX! multiple targets will generally register global commands
797 * multiple times. Only register this one if *one* of the
798 * targets need the command. Hmm... make it a command on the
799 * Jim Tcl target object?
801 register_jim(cmd_ctx, "mcr", jim_mcrmrc, "write coprocessor <cpnum> <op1> <op2> <CRn> <CRm> <value>");
804 if (target->type->mrc == NULL)
806 target->type->mrc = default_mrc;
809 register_jim(cmd_ctx, "mrc", jim_mcrmrc, "read coprocessor <cpnum> <op1> <op2> <CRn> <CRm>");
813 /* a non-invasive way(in terms of patches) to add some code that
814 * runs before the type->write/read_memory implementation
816 target->type->write_memory_imp = target->type->write_memory;
817 target->type->write_memory = target_write_memory_imp;
818 target->type->read_memory_imp = target->type->read_memory;
819 target->type->read_memory = target_read_memory_imp;
820 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
821 target->type->soft_reset_halt = target_soft_reset_halt_imp;
822 target->type->run_algorithm_imp = target->type->run_algorithm;
823 target->type->run_algorithm = target_run_algorithm_imp;
825 if (target->type->mmu == NULL)
827 target->type->mmu = default_mmu;
829 target = target->next;
834 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
836 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
843 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
845 target_event_callback_t **callbacks_p = &target_event_callbacks;
847 if (callback == NULL)
849 return ERROR_INVALID_ARGUMENTS;
854 while ((*callbacks_p)->next)
855 callbacks_p = &((*callbacks_p)->next);
856 callbacks_p = &((*callbacks_p)->next);
859 (*callbacks_p) = malloc(sizeof(target_event_callback_t));
860 (*callbacks_p)->callback = callback;
861 (*callbacks_p)->priv = priv;
862 (*callbacks_p)->next = NULL;
867 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
869 target_timer_callback_t **callbacks_p = &target_timer_callbacks;
872 if (callback == NULL)
874 return ERROR_INVALID_ARGUMENTS;
879 while ((*callbacks_p)->next)
880 callbacks_p = &((*callbacks_p)->next);
881 callbacks_p = &((*callbacks_p)->next);
884 (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
885 (*callbacks_p)->callback = callback;
886 (*callbacks_p)->periodic = periodic;
887 (*callbacks_p)->time_ms = time_ms;
889 gettimeofday(&now, NULL);
890 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
891 time_ms -= (time_ms % 1000);
892 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
893 if ((*callbacks_p)->when.tv_usec > 1000000)
895 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
896 (*callbacks_p)->when.tv_sec += 1;
899 (*callbacks_p)->priv = priv;
900 (*callbacks_p)->next = NULL;
905 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
907 target_event_callback_t **p = &target_event_callbacks;
908 target_event_callback_t *c = target_event_callbacks;
910 if (callback == NULL)
912 return ERROR_INVALID_ARGUMENTS;
917 target_event_callback_t *next = c->next;
918 if ((c->callback == callback) && (c->priv == priv))
932 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
934 target_timer_callback_t **p = &target_timer_callbacks;
935 target_timer_callback_t *c = target_timer_callbacks;
937 if (callback == NULL)
939 return ERROR_INVALID_ARGUMENTS;
944 target_timer_callback_t *next = c->next;
945 if ((c->callback == callback) && (c->priv == priv))
959 int target_call_event_callbacks(target_t *target, enum target_event event)
961 target_event_callback_t *callback = target_event_callbacks;
962 target_event_callback_t *next_callback;
964 if (event == TARGET_EVENT_HALTED)
966 /* execute early halted first */
967 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
970 LOG_DEBUG("target event %i (%s)",
972 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
974 target_handle_event(target, event);
978 next_callback = callback->next;
979 callback->callback(target, event, callback->priv);
980 callback = next_callback;
986 static int target_timer_callback_periodic_restart(
987 target_timer_callback_t *cb, struct timeval *now)
989 int time_ms = cb->time_ms;
990 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
991 time_ms -= (time_ms % 1000);
992 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
993 if (cb->when.tv_usec > 1000000)
995 cb->when.tv_usec = cb->when.tv_usec - 1000000;
996 cb->when.tv_sec += 1;
1001 static int target_call_timer_callback(target_timer_callback_t *cb,
1002 struct timeval *now)
1004 cb->callback(cb->priv);
1007 return target_timer_callback_periodic_restart(cb, now);
1009 return target_unregister_timer_callback(cb->callback, cb->priv);
1012 static int target_call_timer_callbacks_check_time(int checktime)
1017 gettimeofday(&now, NULL);
1019 target_timer_callback_t *callback = target_timer_callbacks;
1022 // cleaning up may unregister and free this callback
1023 target_timer_callback_t *next_callback = callback->next;
1025 bool call_it = callback->callback &&
1026 ((!checktime && callback->periodic) ||
1027 now.tv_sec > callback->when.tv_sec ||
1028 (now.tv_sec == callback->when.tv_sec &&
1029 now.tv_usec >= callback->when.tv_usec));
1033 int retval = target_call_timer_callback(callback, &now);
1034 if (retval != ERROR_OK)
1038 callback = next_callback;
1044 int target_call_timer_callbacks(void)
1046 return target_call_timer_callbacks_check_time(1);
1049 /* invoke periodic callbacks immediately */
1050 int target_call_timer_callbacks_now(void)
1052 return target_call_timer_callbacks_check_time(0);
1055 int target_alloc_working_area(struct target_s *target, uint32_t size, working_area_t **area)
1057 working_area_t *c = target->working_areas;
1058 working_area_t *new_wa = NULL;
1060 /* Reevaluate working area address based on MMU state*/
1061 if (target->working_areas == NULL)
1066 retval = target->type->mmu(target, &enabled);
1067 if (retval != ERROR_OK)
1073 if (target->working_area_phys_spec) {
1074 LOG_DEBUG("MMU disabled, using physical "
1075 "address for working memory 0x%08x",
1076 (unsigned)target->working_area_phys);
1077 target->working_area = target->working_area_phys;
1079 LOG_ERROR("No working memory available. "
1080 "Specify -work-area-phys to target.");
1081 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1084 if (target->working_area_virt_spec) {
1085 LOG_DEBUG("MMU enabled, using virtual "
1086 "address for working memory 0x%08x",
1087 (unsigned)target->working_area_virt);
1088 target->working_area = target->working_area_virt;
1090 LOG_ERROR("No working memory available. "
1091 "Specify -work-area-virt to target.");
1092 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1097 /* only allocate multiples of 4 byte */
1100 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1101 size = (size + 3) & (~3);
1104 /* see if there's already a matching working area */
1107 if ((c->free) && (c->size == size))
1115 /* if not, allocate a new one */
1118 working_area_t **p = &target->working_areas;
1119 uint32_t first_free = target->working_area;
1120 uint32_t free_size = target->working_area_size;
1122 c = target->working_areas;
1125 first_free += c->size;
1126 free_size -= c->size;
1131 if (free_size < size)
1133 LOG_WARNING("not enough working area available(requested %u, free %u)",
1134 (unsigned)(size), (unsigned)(free_size));
1135 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1138 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1140 new_wa = malloc(sizeof(working_area_t));
1141 new_wa->next = NULL;
1142 new_wa->size = size;
1143 new_wa->address = first_free;
1145 if (target->backup_working_area)
1148 new_wa->backup = malloc(new_wa->size);
1149 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1151 free(new_wa->backup);
1158 new_wa->backup = NULL;
1161 /* put new entry in list */
1165 /* mark as used, and return the new (reused) area */
1170 new_wa->user = area;
1175 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
1180 if (restore && target->backup_working_area)
1183 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1189 /* mark user pointer invalid */
1196 int target_free_working_area(struct target_s *target, working_area_t *area)
1198 return target_free_working_area_restore(target, area, 1);
1201 /* free resources and restore memory, if restoring memory fails,
1202 * free up resources anyway
1204 void target_free_all_working_areas_restore(struct target_s *target, int restore)
1206 working_area_t *c = target->working_areas;
1210 working_area_t *next = c->next;
1211 target_free_working_area_restore(target, c, restore);
1221 target->working_areas = NULL;
1224 void target_free_all_working_areas(struct target_s *target)
1226 target_free_all_working_areas_restore(target, 1);
1229 int target_arch_state(struct target_s *target)
1234 LOG_USER("No target has been configured");
1238 LOG_USER("target state: %s", target_state_name( target ));
1240 if (target->state != TARGET_HALTED)
1243 retval = target->type->arch_state(target);
1247 /* Single aligned words are guaranteed to use 16 or 32 bit access
1248 * mode respectively, otherwise data is handled as quickly as
1251 int target_write_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1254 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1255 (int)size, (unsigned)address);
1257 if (!target_was_examined(target))
1259 LOG_ERROR("Target not examined yet");
1267 if ((address + size - 1) < address)
1269 /* GDB can request this when e.g. PC is 0xfffffffc*/
1270 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1276 if (((address % 2) == 0) && (size == 2))
1278 return target_write_memory(target, address, 2, 1, buffer);
1281 /* handle unaligned head bytes */
1284 uint32_t unaligned = 4 - (address % 4);
1286 if (unaligned > size)
1289 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1292 buffer += unaligned;
1293 address += unaligned;
1297 /* handle aligned words */
1300 int aligned = size - (size % 4);
1302 /* use bulk writes above a certain limit. This may have to be changed */
1305 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1310 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1319 /* handle tail writes of less than 4 bytes */
1322 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1329 /* Single aligned words are guaranteed to use 16 or 32 bit access
1330 * mode respectively, otherwise data is handled as quickly as
1333 int target_read_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1336 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1337 (int)size, (unsigned)address);
1339 if (!target_was_examined(target))
1341 LOG_ERROR("Target not examined yet");
1349 if ((address + size - 1) < address)
1351 /* GDB can request this when e.g. PC is 0xfffffffc*/
1352 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1358 if (((address % 2) == 0) && (size == 2))
1360 return target_read_memory(target, address, 2, 1, buffer);
1363 /* handle unaligned head bytes */
1366 uint32_t unaligned = 4 - (address % 4);
1368 if (unaligned > size)
1371 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1374 buffer += unaligned;
1375 address += unaligned;
1379 /* handle aligned words */
1382 int aligned = size - (size % 4);
1384 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1392 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1395 int aligned = size - (size%2);
1396 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1397 if (retval != ERROR_OK)
1404 /* handle tail writes of less than 4 bytes */
1407 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1414 int target_checksum_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* crc)
1419 uint32_t checksum = 0;
1420 if (!target_was_examined(target))
1422 LOG_ERROR("Target not examined yet");
1426 if ((retval = target->type->checksum_memory(target, address,
1427 size, &checksum)) != ERROR_OK)
1429 buffer = malloc(size);
1432 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1433 return ERROR_INVALID_ARGUMENTS;
1435 retval = target_read_buffer(target, address, size, buffer);
1436 if (retval != ERROR_OK)
1442 /* convert to target endianess */
1443 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1445 uint32_t target_data;
1446 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1447 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1450 retval = image_calculate_checksum(buffer, size, &checksum);
1459 int target_blank_check_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* blank)
1462 if (!target_was_examined(target))
1464 LOG_ERROR("Target not examined yet");
1468 if (target->type->blank_check_memory == 0)
1469 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1471 retval = target->type->blank_check_memory(target, address, size, blank);
1476 int target_read_u32(struct target_s *target, uint32_t address, uint32_t *value)
1478 uint8_t value_buf[4];
1479 if (!target_was_examined(target))
1481 LOG_ERROR("Target not examined yet");
1485 int retval = target_read_memory(target, address, 4, 1, value_buf);
1487 if (retval == ERROR_OK)
1489 *value = target_buffer_get_u32(target, value_buf);
1490 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1497 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1504 int target_read_u16(struct target_s *target, uint32_t address, uint16_t *value)
1506 uint8_t value_buf[2];
1507 if (!target_was_examined(target))
1509 LOG_ERROR("Target not examined yet");
1513 int retval = target_read_memory(target, address, 2, 1, value_buf);
1515 if (retval == ERROR_OK)
1517 *value = target_buffer_get_u16(target, value_buf);
1518 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1525 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1532 int target_read_u8(struct target_s *target, uint32_t address, uint8_t *value)
1534 int retval = target_read_memory(target, address, 1, 1, value);
1535 if (!target_was_examined(target))
1537 LOG_ERROR("Target not examined yet");
1541 if (retval == ERROR_OK)
1543 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1550 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1557 int target_write_u32(struct target_s *target, uint32_t address, uint32_t value)
1560 uint8_t value_buf[4];
1561 if (!target_was_examined(target))
1563 LOG_ERROR("Target not examined yet");
1567 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1571 target_buffer_set_u32(target, value_buf, value);
1572 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1574 LOG_DEBUG("failed: %i", retval);
1580 int target_write_u16(struct target_s *target, uint32_t address, uint16_t value)
1583 uint8_t value_buf[2];
1584 if (!target_was_examined(target))
1586 LOG_ERROR("Target not examined yet");
1590 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1594 target_buffer_set_u16(target, value_buf, value);
1595 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1597 LOG_DEBUG("failed: %i", retval);
1603 int target_write_u8(struct target_s *target, uint32_t address, uint8_t value)
1606 if (!target_was_examined(target))
1608 LOG_ERROR("Target not examined yet");
1612 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1615 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1617 LOG_DEBUG("failed: %i", retval);
1623 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1625 target_t *target = all_targets;
1629 target = get_target(args[0]);
1630 if (target == NULL) {
1631 command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1634 if (!target->tap->enabled) {
1635 command_print(cmd_ctx,"Target: TAP %s is disabled, "
1636 "can't be the current target\n",
1637 target->tap->dotted_name);
1641 cmd_ctx->current_target = target->target_number;
1646 target = all_targets;
1647 command_print(cmd_ctx, " TargetName Type Endian TapName State ");
1648 command_print(cmd_ctx, "-- ------------------ ---------- ------ ------------------ ------------");
1654 if (target->tap->enabled)
1655 state = target_state_name( target );
1657 state = "tap-disabled";
1659 if (cmd_ctx->current_target == target->target_number)
1662 /* keep columns lined up to match the headers above */
1663 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1664 target->target_number,
1667 target_get_name(target),
1668 Jim_Nvp_value2name_simple(nvp_target_endian,
1669 target->endianness)->name,
1670 target->tap->dotted_name,
1672 target = target->next;
1678 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1680 static int powerDropout;
1681 static int srstAsserted;
1683 static int runPowerRestore;
1684 static int runPowerDropout;
1685 static int runSrstAsserted;
1686 static int runSrstDeasserted;
1688 static int sense_handler(void)
1690 static int prevSrstAsserted = 0;
1691 static int prevPowerdropout = 0;
1694 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1698 powerRestored = prevPowerdropout && !powerDropout;
1701 runPowerRestore = 1;
1704 long long current = timeval_ms();
1705 static long long lastPower = 0;
1706 int waitMore = lastPower + 2000 > current;
1707 if (powerDropout && !waitMore)
1709 runPowerDropout = 1;
1710 lastPower = current;
1713 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1717 srstDeasserted = prevSrstAsserted && !srstAsserted;
1719 static long long lastSrst = 0;
1720 waitMore = lastSrst + 2000 > current;
1721 if (srstDeasserted && !waitMore)
1723 runSrstDeasserted = 1;
1727 if (!prevSrstAsserted && srstAsserted)
1729 runSrstAsserted = 1;
1732 prevSrstAsserted = srstAsserted;
1733 prevPowerdropout = powerDropout;
1735 if (srstDeasserted || powerRestored)
1737 /* Other than logging the event we can't do anything here.
1738 * Issuing a reset is a particularly bad idea as we might
1739 * be inside a reset already.
1746 static void target_call_event_callbacks_all(enum target_event e) {
1748 target = all_targets;
1750 target_call_event_callbacks(target, e);
1751 target = target->next;
1755 /* process target state changes */
1756 int handle_target(void *priv)
1758 int retval = ERROR_OK;
1760 /* we do not want to recurse here... */
1761 static int recursive = 0;
1766 /* danger! running these procedures can trigger srst assertions and power dropouts.
1767 * We need to avoid an infinite loop/recursion here and we do that by
1768 * clearing the flags after running these events.
1770 int did_something = 0;
1771 if (runSrstAsserted)
1773 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1774 Jim_Eval(interp, "srst_asserted");
1777 if (runSrstDeasserted)
1779 Jim_Eval(interp, "srst_deasserted");
1782 if (runPowerDropout)
1784 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1785 Jim_Eval(interp, "power_dropout");
1788 if (runPowerRestore)
1790 Jim_Eval(interp, "power_restore");
1796 /* clear detect flags */
1800 /* clear action flags */
1802 runSrstAsserted = 0;
1803 runSrstDeasserted = 0;
1804 runPowerRestore = 0;
1805 runPowerDropout = 0;
1810 /* Poll targets for state changes unless that's globally disabled.
1811 * Skip targets that are currently disabled.
1813 for (target_t *target = all_targets;
1814 is_jtag_poll_safe() && target;
1815 target = target->next)
1817 if (!target->tap->enabled)
1820 /* only poll target if we've got power and srst isn't asserted */
1821 if (!powerDropout && !srstAsserted)
1823 /* polling may fail silently until the target has been examined */
1824 if ((retval = target_poll(target)) != ERROR_OK)
1826 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1835 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1844 target = get_current_target(cmd_ctx);
1846 /* list all available registers for the current target */
1849 reg_cache_t *cache = target->reg_cache;
1856 command_print(cmd_ctx, "===== %s", cache->name);
1858 for (i = 0, reg = cache->reg_list;
1859 i < cache->num_regs;
1860 i++, reg++, count++)
1862 /* only print cached values if they are valid */
1864 value = buf_to_str(reg->value,
1866 command_print(cmd_ctx,
1867 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1875 command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1880 cache = cache->next;
1886 /* access a single register by its ordinal number */
1887 if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1890 COMMAND_PARSE_NUMBER(uint, args[0], num);
1892 reg_cache_t *cache = target->reg_cache;
1897 for (i = 0; i < cache->num_regs; i++)
1899 if (count++ == (int)num)
1901 reg = &cache->reg_list[i];
1907 cache = cache->next;
1912 command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1915 } else /* access a single register by its name */
1917 reg = register_get_by_name(target->reg_cache, args[0], 1);
1921 command_print(cmd_ctx, "register %s not found in current target", args[0]);
1926 /* display a register */
1927 if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1929 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1932 if (reg->valid == 0)
1934 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1935 arch_type->get(reg);
1937 value = buf_to_str(reg->value, reg->size, 16);
1938 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1943 /* set register value */
1946 uint8_t *buf = malloc(CEIL(reg->size, 8));
1947 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1949 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1950 arch_type->set(reg, buf);
1952 value = buf_to_str(reg->value, reg->size, 16);
1953 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1961 command_print(cmd_ctx, "usage: reg <#|name> [value]");
1966 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1968 int retval = ERROR_OK;
1969 target_t *target = get_current_target(cmd_ctx);
1973 command_print(cmd_ctx, "background polling: %s",
1974 jtag_poll_get_enabled() ? "on" : "off");
1975 command_print(cmd_ctx, "TAP: %s (%s)",
1976 target->tap->dotted_name,
1977 target->tap->enabled ? "enabled" : "disabled");
1978 if (!target->tap->enabled)
1980 if ((retval = target_poll(target)) != ERROR_OK)
1982 if ((retval = target_arch_state(target)) != ERROR_OK)
1988 if (strcmp(args[0], "on") == 0)
1990 jtag_poll_set_enabled(true);
1992 else if (strcmp(args[0], "off") == 0)
1994 jtag_poll_set_enabled(false);
1998 command_print(cmd_ctx, "arg is \"on\" or \"off\"");
2002 return ERROR_COMMAND_SYNTAX_ERROR;
2008 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2011 return ERROR_COMMAND_SYNTAX_ERROR;
2016 int retval = parse_uint(args[0], &ms);
2017 if (ERROR_OK != retval)
2019 command_print(cmd_ctx, "usage: %s [seconds]", cmd);
2020 return ERROR_COMMAND_SYNTAX_ERROR;
2022 // convert seconds (given) to milliseconds (needed)
2026 target_t *target = get_current_target(cmd_ctx);
2027 return target_wait_state(target, TARGET_HALTED, ms);
2030 /* wait for target state to change. The trick here is to have a low
2031 * latency for short waits and not to suck up all the CPU time
2034 * After 500ms, keep_alive() is invoked
2036 int target_wait_state(target_t *target, enum target_state state, int ms)
2039 long long then = 0, cur;
2044 if ((retval = target_poll(target)) != ERROR_OK)
2046 if (target->state == state)
2054 then = timeval_ms();
2055 LOG_DEBUG("waiting for target %s...",
2056 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2064 if ((cur-then) > ms)
2066 LOG_ERROR("timed out while waiting for target %s",
2067 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2075 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2079 target_t *target = get_current_target(cmd_ctx);
2080 int retval = target_halt(target);
2081 if (ERROR_OK != retval)
2087 retval = parse_uint(args[0], &wait);
2088 if (ERROR_OK != retval)
2089 return ERROR_COMMAND_SYNTAX_ERROR;
2094 return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
2097 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2099 target_t *target = get_current_target(cmd_ctx);
2101 LOG_USER("requesting target halt and executing a soft reset");
2103 target->type->soft_reset_halt(target);
2108 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2111 return ERROR_COMMAND_SYNTAX_ERROR;
2113 enum target_reset_mode reset_mode = RESET_RUN;
2117 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2118 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2119 return ERROR_COMMAND_SYNTAX_ERROR;
2121 reset_mode = n->value;
2124 /* reset *all* targets */
2125 return target_process_reset(cmd_ctx, reset_mode);
2129 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2133 return ERROR_COMMAND_SYNTAX_ERROR;
2135 target_t *target = get_current_target(cmd_ctx);
2136 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2138 /* with no args, resume from current pc, addr = 0,
2139 * with one arguments, addr = args[0],
2140 * handle breakpoints, not debugging */
2144 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2148 return target_resume(target, current, addr, 1, 0);
2151 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2154 return ERROR_COMMAND_SYNTAX_ERROR;
2158 /* with no args, step from current pc, addr = 0,
2159 * with one argument addr = args[0],
2160 * handle breakpoints, debugging */
2165 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2169 target_t *target = get_current_target(cmd_ctx);
2171 return target->type->step(target, current_pc, addr, 1);
2174 static void handle_md_output(struct command_context_s *cmd_ctx,
2175 struct target_s *target, uint32_t address, unsigned size,
2176 unsigned count, const uint8_t *buffer)
2178 const unsigned line_bytecnt = 32;
2179 unsigned line_modulo = line_bytecnt / size;
2181 char output[line_bytecnt * 4 + 1];
2182 unsigned output_len = 0;
2184 const char *value_fmt;
2186 case 4: value_fmt = "%8.8x "; break;
2187 case 2: value_fmt = "%4.2x "; break;
2188 case 1: value_fmt = "%2.2x "; break;
2190 LOG_ERROR("invalid memory read size: %u", size);
2194 for (unsigned i = 0; i < count; i++)
2196 if (i % line_modulo == 0)
2198 output_len += snprintf(output + output_len,
2199 sizeof(output) - output_len,
2201 (unsigned)(address + (i*size)));
2205 const uint8_t *value_ptr = buffer + i * size;
2207 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2208 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2209 case 1: value = *value_ptr;
2211 output_len += snprintf(output + output_len,
2212 sizeof(output) - output_len,
2215 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2217 command_print(cmd_ctx, "%s", output);
2223 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2226 return ERROR_COMMAND_SYNTAX_ERROR;
2230 case 'w': size = 4; break;
2231 case 'h': size = 2; break;
2232 case 'b': size = 1; break;
2233 default: return ERROR_COMMAND_SYNTAX_ERROR;
2236 bool physical=strcmp(args[0], "phys")==0;
2237 int (*fn)(struct target_s *target,
2238 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2243 fn=target_read_phys_memory;
2246 fn=target_read_memory;
2248 if ((argc < 1) || (argc > 2))
2250 return ERROR_COMMAND_SYNTAX_ERROR;
2254 COMMAND_PARSE_NUMBER(u32, args[0], address);
2258 COMMAND_PARSE_NUMBER(uint, args[1], count);
2260 uint8_t *buffer = calloc(count, size);
2262 target_t *target = get_current_target(cmd_ctx);
2263 int retval = fn(target, address, size, count, buffer);
2264 if (ERROR_OK == retval)
2265 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2272 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2276 return ERROR_COMMAND_SYNTAX_ERROR;
2278 bool physical=strcmp(args[0], "phys")==0;
2279 int (*fn)(struct target_s *target,
2280 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2285 fn=target_write_phys_memory;
2288 fn=target_write_memory;
2290 if ((argc < 2) || (argc > 3))
2291 return ERROR_COMMAND_SYNTAX_ERROR;
2294 COMMAND_PARSE_NUMBER(u32, args[0], address);
2297 COMMAND_PARSE_NUMBER(u32, args[1], value);
2301 COMMAND_PARSE_NUMBER(uint, args[2], count);
2303 target_t *target = get_current_target(cmd_ctx);
2305 uint8_t value_buf[4];
2310 target_buffer_set_u32(target, value_buf, value);
2314 target_buffer_set_u16(target, value_buf, value);
2318 value_buf[0] = value;
2321 return ERROR_COMMAND_SYNTAX_ERROR;
2323 for (unsigned i = 0; i < count; i++)
2325 int retval = fn(target,
2326 address + i * wordsize, wordsize, 1, value_buf);
2327 if (ERROR_OK != retval)
2336 static int parse_load_image_command_args(struct command_context_s *cmd_ctx,
2337 char **args, int argc, image_t *image,
2338 uint32_t *min_address, uint32_t *max_address)
2340 if (argc < 1 || argc > 5)
2341 return ERROR_COMMAND_SYNTAX_ERROR;
2343 /* a base address isn't always necessary,
2344 * default to 0x0 (i.e. don't relocate) */
2348 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2349 image->base_address = addr;
2350 image->base_address_set = 1;
2353 image->base_address_set = 0;
2355 image->start_address_set = 0;
2359 COMMAND_PARSE_NUMBER(u32, args[3], *min_address);
2363 COMMAND_PARSE_NUMBER(u32, args[4], *max_address);
2364 // use size (given) to find max (required)
2365 *max_address += *min_address;
2368 if (*min_address > *max_address)
2369 return ERROR_COMMAND_SYNTAX_ERROR;
2374 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2378 uint32_t image_size;
2379 uint32_t min_address = 0;
2380 uint32_t max_address = 0xffffffff;
2384 int retval = parse_load_image_command_args(cmd_ctx, args, argc,
2385 &image, &min_address, &max_address);
2386 if (ERROR_OK != retval)
2389 target_t *target = get_current_target(cmd_ctx);
2391 struct duration bench;
2392 duration_start(&bench);
2394 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2401 for (i = 0; i < image.num_sections; i++)
2403 buffer = malloc(image.sections[i].size);
2406 command_print(cmd_ctx,
2407 "error allocating buffer for section (%d bytes)",
2408 (int)(image.sections[i].size));
2412 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2418 uint32_t offset = 0;
2419 uint32_t length = buf_cnt;
2421 /* DANGER!!! beware of unsigned comparision here!!! */
2423 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2424 (image.sections[i].base_address < max_address))
2426 if (image.sections[i].base_address < min_address)
2428 /* clip addresses below */
2429 offset += min_address-image.sections[i].base_address;
2433 if (image.sections[i].base_address + buf_cnt > max_address)
2435 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2438 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2443 image_size += length;
2444 command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2445 (unsigned int)length,
2446 image.sections[i].base_address + offset);
2452 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2454 command_print(cmd_ctx, "downloaded %" PRIu32 " bytes "
2455 "in %fs (%0.3f kb/s)", image_size,
2456 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2459 image_close(&image);
2465 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2469 uint8_t buffer[560];
2473 target_t *target = get_current_target(cmd_ctx);
2477 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2482 COMMAND_PARSE_NUMBER(u32, args[1], address);
2484 COMMAND_PARSE_NUMBER(u32, args[2], size);
2486 if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2491 struct duration bench;
2492 duration_start(&bench);
2494 int retval = ERROR_OK;
2497 uint32_t size_written;
2498 uint32_t this_run_size = (size > 560) ? 560 : size;
2499 retval = target_read_buffer(target, address, this_run_size, buffer);
2500 if (retval != ERROR_OK)
2505 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2506 if (retval != ERROR_OK)
2511 size -= this_run_size;
2512 address += this_run_size;
2515 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2518 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2520 command_print(cmd_ctx,
2521 "dumped %lld bytes in %fs (%0.3f kb/s)", fileio.size,
2522 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2528 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2532 uint32_t image_size;
2535 uint32_t checksum = 0;
2536 uint32_t mem_checksum = 0;
2540 target_t *target = get_current_target(cmd_ctx);
2544 return ERROR_COMMAND_SYNTAX_ERROR;
2549 LOG_ERROR("no target selected");
2553 struct duration bench;
2554 duration_start(&bench);
2559 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2560 image.base_address = addr;
2561 image.base_address_set = 1;
2565 image.base_address_set = 0;
2566 image.base_address = 0x0;
2569 image.start_address_set = 0;
2571 if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2578 for (i = 0; i < image.num_sections; i++)
2580 buffer = malloc(image.sections[i].size);
2583 command_print(cmd_ctx,
2584 "error allocating buffer for section (%d bytes)",
2585 (int)(image.sections[i].size));
2588 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2596 /* calculate checksum of image */
2597 image_calculate_checksum(buffer, buf_cnt, &checksum);
2599 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2600 if (retval != ERROR_OK)
2606 if (checksum != mem_checksum)
2608 /* failed crc checksum, fall back to a binary compare */
2611 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2613 data = (uint8_t*)malloc(buf_cnt);
2615 /* Can we use 32bit word accesses? */
2617 int count = buf_cnt;
2618 if ((count % 4) == 0)
2623 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2624 if (retval == ERROR_OK)
2627 for (t = 0; t < buf_cnt; t++)
2629 if (data[t] != buffer[t])
2631 command_print(cmd_ctx,
2632 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2633 (unsigned)(t + image.sections[i].base_address),
2638 retval = ERROR_FAIL;
2652 command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2653 image.sections[i].base_address,
2658 image_size += buf_cnt;
2661 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2663 command_print(cmd_ctx, "verified %" PRIu32 " bytes "
2664 "in %fs (%0.3f kb/s)", image_size,
2665 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2668 image_close(&image);
2673 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2675 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2678 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2680 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2683 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2685 target_t *target = get_current_target(cmd_ctx);
2686 breakpoint_t *breakpoint = target->breakpoints;
2689 if (breakpoint->type == BKPT_SOFT)
2691 char* buf = buf_to_str(breakpoint->orig_instr,
2692 breakpoint->length, 16);
2693 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2694 breakpoint->address,
2696 breakpoint->set, buf);
2701 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2702 breakpoint->address,
2703 breakpoint->length, breakpoint->set);
2706 breakpoint = breakpoint->next;
2711 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2712 uint32_t addr, uint32_t length, int hw)
2714 target_t *target = get_current_target(cmd_ctx);
2715 int retval = breakpoint_add(target, addr, length, hw);
2716 if (ERROR_OK == retval)
2717 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2719 LOG_ERROR("Failure setting breakpoint");
2723 static int handle_bp_command(struct command_context_s *cmd_ctx,
2724 char *cmd, char **args, int argc)
2727 return handle_bp_command_list(cmd_ctx);
2729 if (argc < 2 || argc > 3)
2731 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2732 return ERROR_COMMAND_SYNTAX_ERROR;
2736 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2738 COMMAND_PARSE_NUMBER(u32, args[1], length);
2743 if (strcmp(args[2], "hw") == 0)
2746 return ERROR_COMMAND_SYNTAX_ERROR;
2749 return handle_bp_command_set(cmd_ctx, addr, length, hw);
2752 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2755 return ERROR_COMMAND_SYNTAX_ERROR;
2758 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2760 target_t *target = get_current_target(cmd_ctx);
2761 breakpoint_remove(target, addr);
2766 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2768 target_t *target = get_current_target(cmd_ctx);
2772 watchpoint_t *watchpoint = target->watchpoints;
2776 command_print(cmd_ctx,
2777 "address: 0x%8.8" PRIx32 ", len: 0x%8.8x, r/w/a: %i, value: 0x%8.8" PRIx32 ", mask: 0x%8.8" PRIx32 "",
2778 watchpoint->address,
2780 (int)(watchpoint->rw),
2783 watchpoint = watchpoint->next;
2788 enum watchpoint_rw type = WPT_ACCESS;
2790 uint32_t length = 0;
2791 uint32_t data_value = 0x0;
2792 uint32_t data_mask = 0xffffffff;
2797 COMMAND_PARSE_NUMBER(u32, args[4], data_mask);
2800 COMMAND_PARSE_NUMBER(u32, args[3], data_value);
2815 LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2816 return ERROR_COMMAND_SYNTAX_ERROR;
2820 COMMAND_PARSE_NUMBER(u32, args[1], length);
2821 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2825 command_print(cmd_ctx, "usage: wp [address length "
2826 "[(r|w|a) [value [mask]]]]");
2827 return ERROR_COMMAND_SYNTAX_ERROR;
2830 int retval = watchpoint_add(target, addr, length, type,
2831 data_value, data_mask);
2832 if (ERROR_OK != retval)
2833 LOG_ERROR("Failure setting watchpoints");
2838 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2841 return ERROR_COMMAND_SYNTAX_ERROR;
2844 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2846 target_t *target = get_current_target(cmd_ctx);
2847 watchpoint_remove(target, addr);
2854 * Translate a virtual address to a physical address.
2856 * The low-level target implementation must have logged a detailed error
2857 * which is forwarded to telnet/GDB session.
2859 static int handle_virt2phys_command(command_context_t *cmd_ctx,
2860 char *cmd, char **args, int argc)
2863 return ERROR_COMMAND_SYNTAX_ERROR;
2866 COMMAND_PARSE_NUMBER(u32, args[0], va);
2869 target_t *target = get_current_target(cmd_ctx);
2870 int retval = target->type->virt2phys(target, va, &pa);
2871 if (retval == ERROR_OK)
2872 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2877 static void writeData(FILE *f, const void *data, size_t len)
2879 size_t written = fwrite(data, 1, len, f);
2881 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2884 static void writeLong(FILE *f, int l)
2887 for (i = 0; i < 4; i++)
2889 char c = (l >> (i*8))&0xff;
2890 writeData(f, &c, 1);
2895 static void writeString(FILE *f, char *s)
2897 writeData(f, s, strlen(s));
2900 /* Dump a gmon.out histogram file. */
2901 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
2904 FILE *f = fopen(filename, "w");
2907 writeString(f, "gmon");
2908 writeLong(f, 0x00000001); /* Version */
2909 writeLong(f, 0); /* padding */
2910 writeLong(f, 0); /* padding */
2911 writeLong(f, 0); /* padding */
2913 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2914 writeData(f, &zero, 1);
2916 /* figure out bucket size */
2917 uint32_t min = samples[0];
2918 uint32_t max = samples[0];
2919 for (i = 0; i < sampleNum; i++)
2921 if (min > samples[i])
2925 if (max < samples[i])
2931 int addressSpace = (max-min + 1);
2933 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2934 uint32_t length = addressSpace;
2935 if (length > maxBuckets)
2937 length = maxBuckets;
2939 int *buckets = malloc(sizeof(int)*length);
2940 if (buckets == NULL)
2945 memset(buckets, 0, sizeof(int)*length);
2946 for (i = 0; i < sampleNum;i++)
2948 uint32_t address = samples[i];
2949 long long a = address-min;
2950 long long b = length-1;
2951 long long c = addressSpace-1;
2952 int index = (a*b)/c; /* danger!!!! int32 overflows */
2956 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2957 writeLong(f, min); /* low_pc */
2958 writeLong(f, max); /* high_pc */
2959 writeLong(f, length); /* # of samples */
2960 writeLong(f, 64000000); /* 64MHz */
2961 writeString(f, "seconds");
2962 for (i = 0; i < (15-strlen("seconds")); i++)
2963 writeData(f, &zero, 1);
2964 writeString(f, "s");
2966 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2968 char *data = malloc(2*length);
2971 for (i = 0; i < length;i++)
2980 data[i*2 + 1]=(val >> 8)&0xff;
2983 writeData(f, data, length * 2);
2993 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2994 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2996 target_t *target = get_current_target(cmd_ctx);
2997 struct timeval timeout, now;
2999 gettimeofday(&timeout, NULL);
3002 return ERROR_COMMAND_SYNTAX_ERROR;
3005 COMMAND_PARSE_NUMBER(uint, args[0], offset);
3007 timeval_add_time(&timeout, offset, 0);
3009 command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3011 static const int maxSample = 10000;
3012 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3013 if (samples == NULL)
3017 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3018 reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
3023 target_poll(target);
3024 if (target->state == TARGET_HALTED)
3026 uint32_t t=*((uint32_t *)reg->value);
3027 samples[numSamples++]=t;
3028 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3029 target_poll(target);
3030 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3031 } else if (target->state == TARGET_RUNNING)
3033 /* We want to quickly sample the PC. */
3034 if ((retval = target_halt(target)) != ERROR_OK)
3041 command_print(cmd_ctx, "Target not halted or running");
3045 if (retval != ERROR_OK)
3050 gettimeofday(&now, NULL);
3051 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3053 command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3054 if ((retval = target_poll(target)) != ERROR_OK)
3059 if (target->state == TARGET_HALTED)
3061 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3063 if ((retval = target_poll(target)) != ERROR_OK)
3068 writeGmon(samples, numSamples, args[1]);
3069 command_print(cmd_ctx, "Wrote %s", args[1]);
3078 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3081 Jim_Obj *nameObjPtr, *valObjPtr;
3084 namebuf = alloc_printf("%s(%d)", varname, idx);
3088 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3089 valObjPtr = Jim_NewIntObj(interp, val);
3090 if (!nameObjPtr || !valObjPtr)
3096 Jim_IncrRefCount(nameObjPtr);
3097 Jim_IncrRefCount(valObjPtr);
3098 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3099 Jim_DecrRefCount(interp, nameObjPtr);
3100 Jim_DecrRefCount(interp, valObjPtr);
3102 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3106 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3108 command_context_t *context;
3111 context = Jim_GetAssocData(interp, "context");
3112 if (context == NULL)
3114 LOG_ERROR("mem2array: no command context");
3117 target = get_current_target(context);
3120 LOG_ERROR("mem2array: no current target");
3124 return target_mem2array(interp, target, argc-1, argv + 1);
3127 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3135 const char *varname;
3136 uint8_t buffer[4096];
3140 /* argv[1] = name of array to receive the data
3141 * argv[2] = desired width
3142 * argv[3] = memory address
3143 * argv[4] = count of times to read
3146 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3149 varname = Jim_GetString(argv[0], &len);
3150 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3152 e = Jim_GetLong(interp, argv[1], &l);
3158 e = Jim_GetLong(interp, argv[2], &l);
3163 e = Jim_GetLong(interp, argv[3], &l);
3179 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3180 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3184 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3185 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3188 if ((addr + (len * width)) < addr) {
3189 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3190 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3193 /* absurd transfer size? */
3195 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3196 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3201 ((width == 2) && ((addr & 1) == 0)) ||
3202 ((width == 4) && ((addr & 3) == 0))) {
3206 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3207 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3210 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3221 /* Slurp... in buffer size chunks */
3223 count = len; /* in objects.. */
3224 if (count > (sizeof(buffer)/width)) {
3225 count = (sizeof(buffer)/width);
3228 retval = target_read_memory(target, addr, width, count, buffer);
3229 if (retval != ERROR_OK) {
3231 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3235 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3236 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3240 v = 0; /* shut up gcc */
3241 for (i = 0 ;i < count ;i++, n++) {
3244 v = target_buffer_get_u32(target, &buffer[i*width]);
3247 v = target_buffer_get_u16(target, &buffer[i*width]);
3250 v = buffer[i] & 0x0ff;
3253 new_int_array_element(interp, varname, n, v);
3259 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3264 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3267 Jim_Obj *nameObjPtr, *valObjPtr;
3271 namebuf = alloc_printf("%s(%d)", varname, idx);
3275 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3282 Jim_IncrRefCount(nameObjPtr);
3283 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3284 Jim_DecrRefCount(interp, nameObjPtr);
3286 if (valObjPtr == NULL)
3289 result = Jim_GetLong(interp, valObjPtr, &l);
3290 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3295 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3297 command_context_t *context;
3300 context = Jim_GetAssocData(interp, "context");
3301 if (context == NULL) {
3302 LOG_ERROR("array2mem: no command context");
3305 target = get_current_target(context);
3306 if (target == NULL) {
3307 LOG_ERROR("array2mem: no current target");
3311 return target_array2mem(interp,target, argc-1, argv + 1);
3313 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3321 const char *varname;
3322 uint8_t buffer[4096];
3326 /* argv[1] = name of array to get the data
3327 * argv[2] = desired width
3328 * argv[3] = memory address
3329 * argv[4] = count to write
3332 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3335 varname = Jim_GetString(argv[0], &len);
3336 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3338 e = Jim_GetLong(interp, argv[1], &l);
3344 e = Jim_GetLong(interp, argv[2], &l);
3349 e = Jim_GetLong(interp, argv[3], &l);
3365 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3366 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3370 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3371 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3374 if ((addr + (len * width)) < addr) {
3375 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3376 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3379 /* absurd transfer size? */
3381 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3382 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3387 ((width == 2) && ((addr & 1) == 0)) ||
3388 ((width == 4) && ((addr & 3) == 0))) {
3392 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3393 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3396 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3407 /* Slurp... in buffer size chunks */
3409 count = len; /* in objects.. */
3410 if (count > (sizeof(buffer)/width)) {
3411 count = (sizeof(buffer)/width);
3414 v = 0; /* shut up gcc */
3415 for (i = 0 ;i < count ;i++, n++) {
3416 get_int_array_element(interp, varname, n, &v);
3419 target_buffer_set_u32(target, &buffer[i*width], v);
3422 target_buffer_set_u16(target, &buffer[i*width], v);
3425 buffer[i] = v & 0x0ff;
3431 retval = target_write_memory(target, addr, width, count, buffer);
3432 if (retval != ERROR_OK) {
3434 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3438 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3439 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3445 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3450 void target_all_handle_event(enum target_event e)
3454 LOG_DEBUG("**all*targets: event: %d, %s",
3456 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3458 target = all_targets;
3460 target_handle_event(target, e);
3461 target = target->next;
3466 /* FIX? should we propagate errors here rather than printing them
3469 void target_handle_event(target_t *target, enum target_event e)
3471 target_event_action_t *teap;
3473 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3474 if (teap->event == e) {
3475 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3476 target->target_number,
3478 target_get_name(target),
3480 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3481 Jim_GetString(teap->body, NULL));
3482 if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3484 Jim_PrintErrorMessage(interp);
3490 enum target_cfg_param {
3493 TCFG_WORK_AREA_VIRT,
3494 TCFG_WORK_AREA_PHYS,
3495 TCFG_WORK_AREA_SIZE,
3496 TCFG_WORK_AREA_BACKUP,
3499 TCFG_CHAIN_POSITION,
3502 static Jim_Nvp nvp_config_opts[] = {
3503 { .name = "-type", .value = TCFG_TYPE },
3504 { .name = "-event", .value = TCFG_EVENT },
3505 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3506 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3507 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3508 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3509 { .name = "-endian" , .value = TCFG_ENDIAN },
3510 { .name = "-variant", .value = TCFG_VARIANT },
3511 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3513 { .name = NULL, .value = -1 }
3516 static int target_configure(Jim_GetOptInfo *goi, target_t *target)
3524 /* parse config or cget options ... */
3525 while (goi->argc > 0) {
3526 Jim_SetEmptyResult(goi->interp);
3527 /* Jim_GetOpt_Debug(goi); */
3529 if (target->type->target_jim_configure) {
3530 /* target defines a configure function */
3531 /* target gets first dibs on parameters */
3532 e = (*(target->type->target_jim_configure))(target, goi);
3541 /* otherwise we 'continue' below */
3543 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3545 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3551 if (goi->isconfigure) {
3552 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3556 if (goi->argc != 0) {
3557 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3561 Jim_SetResultString(goi->interp, target_get_name(target), -1);
3565 if (goi->argc == 0) {
3566 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3570 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3572 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3576 if (goi->isconfigure) {
3577 if (goi->argc != 1) {
3578 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3582 if (goi->argc != 0) {
3583 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3589 target_event_action_t *teap;
3591 teap = target->event_action;
3592 /* replace existing? */
3594 if (teap->event == (enum target_event)n->value) {
3600 if (goi->isconfigure) {
3601 bool replace = true;
3604 teap = calloc(1, sizeof(*teap));
3607 teap->event = n->value;
3608 Jim_GetOpt_Obj(goi, &o);
3610 Jim_DecrRefCount(interp, teap->body);
3612 teap->body = Jim_DuplicateObj(goi->interp, o);
3615 * Tcl/TK - "tk events" have a nice feature.
3616 * See the "BIND" command.
3617 * We should support that here.
3618 * You can specify %X and %Y in the event code.
3619 * The idea is: %T - target name.
3620 * The idea is: %N - target number
3621 * The idea is: %E - event name.
3623 Jim_IncrRefCount(teap->body);
3627 /* add to head of event list */
3628 teap->next = target->event_action;
3629 target->event_action = teap;
3631 Jim_SetEmptyResult(goi->interp);
3635 Jim_SetEmptyResult(goi->interp);
3637 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3644 case TCFG_WORK_AREA_VIRT:
3645 if (goi->isconfigure) {
3646 target_free_all_working_areas(target);
3647 e = Jim_GetOpt_Wide(goi, &w);
3651 target->working_area_virt = w;
3652 target->working_area_virt_spec = true;
3654 if (goi->argc != 0) {
3658 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3662 case TCFG_WORK_AREA_PHYS:
3663 if (goi->isconfigure) {
3664 target_free_all_working_areas(target);
3665 e = Jim_GetOpt_Wide(goi, &w);
3669 target->working_area_phys = w;
3670 target->working_area_phys_spec = true;
3672 if (goi->argc != 0) {
3676 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3680 case TCFG_WORK_AREA_SIZE:
3681 if (goi->isconfigure) {
3682 target_free_all_working_areas(target);
3683 e = Jim_GetOpt_Wide(goi, &w);
3687 target->working_area_size = w;
3689 if (goi->argc != 0) {
3693 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3697 case TCFG_WORK_AREA_BACKUP:
3698 if (goi->isconfigure) {
3699 target_free_all_working_areas(target);
3700 e = Jim_GetOpt_Wide(goi, &w);
3704 /* make this exactly 1 or 0 */
3705 target->backup_working_area = (!!w);
3707 if (goi->argc != 0) {
3711 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3712 /* loop for more e*/
3716 if (goi->isconfigure) {
3717 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3719 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3722 target->endianness = n->value;
3724 if (goi->argc != 0) {
3728 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3729 if (n->name == NULL) {
3730 target->endianness = TARGET_LITTLE_ENDIAN;
3731 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3733 Jim_SetResultString(goi->interp, n->name, -1);
3738 if (goi->isconfigure) {
3739 if (goi->argc < 1) {
3740 Jim_SetResult_sprintf(goi->interp,
3745 if (target->variant) {
3746 free((void *)(target->variant));
3748 e = Jim_GetOpt_String(goi, &cp, NULL);
3749 target->variant = strdup(cp);
3751 if (goi->argc != 0) {
3755 Jim_SetResultString(goi->interp, target->variant,-1);
3758 case TCFG_CHAIN_POSITION:
3759 if (goi->isconfigure) {
3762 target_free_all_working_areas(target);
3763 e = Jim_GetOpt_Obj(goi, &o);
3767 tap = jtag_tap_by_jim_obj(goi->interp, o);
3771 /* make this exactly 1 or 0 */
3774 if (goi->argc != 0) {
3778 Jim_SetResultString(interp, target->tap->dotted_name, -1);
3779 /* loop for more e*/
3782 } /* while (goi->argc) */
3785 /* done - we return */
3789 /** this is the 'tcl' handler for the target specific command */
3790 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3795 uint8_t target_buf[32];
3798 struct command_context_s *cmd_ctx;
3805 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3806 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3807 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3808 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3816 TS_CMD_INVOKE_EVENT,
3819 static const Jim_Nvp target_options[] = {
3820 { .name = "configure", .value = TS_CMD_CONFIGURE },
3821 { .name = "cget", .value = TS_CMD_CGET },
3822 { .name = "mww", .value = TS_CMD_MWW },
3823 { .name = "mwh", .value = TS_CMD_MWH },
3824 { .name = "mwb", .value = TS_CMD_MWB },
3825 { .name = "mdw", .value = TS_CMD_MDW },
3826 { .name = "mdh", .value = TS_CMD_MDH },
3827 { .name = "mdb", .value = TS_CMD_MDB },
3828 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3829 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3830 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3831 { .name = "curstate", .value = TS_CMD_CURSTATE },
3833 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3834 { .name = "arp_poll", .value = TS_CMD_POLL },
3835 { .name = "arp_reset", .value = TS_CMD_RESET },
3836 { .name = "arp_halt", .value = TS_CMD_HALT },
3837 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3838 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3840 { .name = NULL, .value = -1 },
3843 /* go past the "command" */
3844 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3846 target = Jim_CmdPrivData(goi.interp);
3847 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3849 /* commands here are in an NVP table */
3850 e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3852 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3855 /* Assume blank result */
3856 Jim_SetEmptyResult(goi.interp);
3859 case TS_CMD_CONFIGURE:
3861 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3864 goi.isconfigure = 1;
3865 return target_configure(&goi, target);
3867 // some things take params
3869 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3872 goi.isconfigure = 0;
3873 return target_configure(&goi, target);
3881 * argv[3] = optional count.
3884 if ((goi.argc == 2) || (goi.argc == 3)) {
3888 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3892 e = Jim_GetOpt_Wide(&goi, &a);
3897 e = Jim_GetOpt_Wide(&goi, &b);
3901 if (goi.argc == 3) {
3902 e = Jim_GetOpt_Wide(&goi, &c);
3912 target_buffer_set_u32(target, target_buf, b);
3916 target_buffer_set_u16(target, target_buf, b);
3920 target_buffer_set_u8(target, target_buf, b);
3924 for (x = 0 ; x < c ; x++) {
3925 e = target_write_memory(target, a, b, 1, target_buf);
3926 if (e != ERROR_OK) {
3927 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3940 /* argv[0] = command
3942 * argv[2] = optional count
3944 if ((goi.argc == 2) || (goi.argc == 3)) {
3945 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3948 e = Jim_GetOpt_Wide(&goi, &a);
3953 e = Jim_GetOpt_Wide(&goi, &c);
3960 b = 1; /* shut up gcc */
3973 /* convert to "bytes" */
3975 /* count is now in 'BYTES' */
3981 e = target_read_memory(target, a, b, y / b, target_buf);
3982 if (e != ERROR_OK) {
3983 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
3987 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
3990 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
3991 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
3992 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
3994 for (; (x < 16) ; x += 4) {
3995 Jim_fprintf(interp, interp->cookie_stdout, " ");
3999 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
4000 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
4001 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4003 for (; (x < 16) ; x += 2) {
4004 Jim_fprintf(interp, interp->cookie_stdout, " ");
4009 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4010 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4011 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4013 for (; (x < 16) ; x += 1) {
4014 Jim_fprintf(interp, interp->cookie_stdout, " ");
4018 /* ascii-ify the bytes */
4019 for (x = 0 ; x < y ; x++) {
4020 if ((target_buf[x] >= 0x20) &&
4021 (target_buf[x] <= 0x7e)) {
4025 target_buf[x] = '.';
4030 target_buf[x] = ' ';
4035 /* print - with a newline */
4036 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4042 case TS_CMD_MEM2ARRAY:
4043 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4045 case TS_CMD_ARRAY2MEM:
4046 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4048 case TS_CMD_EXAMINE:
4050 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4053 if (!target->tap->enabled)
4054 goto err_tap_disabled;
4055 e = target->type->examine(target);
4056 if (e != ERROR_OK) {
4057 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4063 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4066 if (!target->tap->enabled)
4067 goto err_tap_disabled;
4068 if (!(target_was_examined(target))) {
4069 e = ERROR_TARGET_NOT_EXAMINED;
4071 e = target->type->poll(target);
4073 if (e != ERROR_OK) {
4074 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4081 if (goi.argc != 2) {
4082 Jim_WrongNumArgs(interp, 2, argv,
4083 "([tT]|[fF]|assert|deassert) BOOL");
4086 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4088 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4091 /* the halt or not param */
4092 e = Jim_GetOpt_Wide(&goi, &a);
4096 if (!target->tap->enabled)
4097 goto err_tap_disabled;
4098 if (!target->type->assert_reset
4099 || !target->type->deassert_reset) {
4100 Jim_SetResult_sprintf(interp,
4101 "No target-specific reset for %s",
4105 /* determine if we should halt or not. */
4106 target->reset_halt = !!a;
4107 /* When this happens - all workareas are invalid. */
4108 target_free_all_working_areas_restore(target, 0);
4111 if (n->value == NVP_ASSERT) {
4112 e = target->type->assert_reset(target);
4114 e = target->type->deassert_reset(target);
4116 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4119 Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4122 if (!target->tap->enabled)
4123 goto err_tap_disabled;
4124 e = target->type->halt(target);
4125 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4126 case TS_CMD_WAITSTATE:
4127 /* params: <name> statename timeoutmsecs */
4128 if (goi.argc != 2) {
4129 Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4132 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4134 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4137 e = Jim_GetOpt_Wide(&goi, &a);
4141 if (!target->tap->enabled)
4142 goto err_tap_disabled;
4143 e = target_wait_state(target, n->value, a);
4144 if (e != ERROR_OK) {
4145 Jim_SetResult_sprintf(goi.interp,
4146 "target: %s wait %s fails (%d) %s",
4149 e, target_strerror_safe(e));
4154 case TS_CMD_EVENTLIST:
4155 /* List for human, Events defined for this target.
4156 * scripts/programs should use 'name cget -event NAME'
4159 target_event_action_t *teap;
4160 teap = target->event_action;
4161 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4162 target->target_number,
4164 command_print(cmd_ctx, "%-25s | Body", "Event");
4165 command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4167 command_print(cmd_ctx,
4169 Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4170 Jim_GetString(teap->body, NULL));
4173 command_print(cmd_ctx, "***END***");
4176 case TS_CMD_CURSTATE:
4177 if (goi.argc != 0) {
4178 Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4181 Jim_SetResultString(goi.interp,
4182 target_state_name( target ),
4185 case TS_CMD_INVOKE_EVENT:
4186 if (goi.argc != 1) {
4187 Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4190 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4192 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4195 target_handle_event(target, n->value);
4201 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4205 static int target_create(Jim_GetOptInfo *goi)
4214 struct command_context_s *cmd_ctx;
4216 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4217 if (goi->argc < 3) {
4218 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4223 Jim_GetOpt_Obj(goi, &new_cmd);
4224 /* does this command exist? */
4225 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4227 cp = Jim_GetString(new_cmd, NULL);
4228 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4233 e = Jim_GetOpt_String(goi, &cp2, NULL);
4235 /* now does target type exist */
4236 for (x = 0 ; target_types[x] ; x++) {
4237 if (0 == strcmp(cp, target_types[x]->name)) {
4242 if (target_types[x] == NULL) {
4243 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4244 for (x = 0 ; target_types[x] ; x++) {
4245 if (target_types[x + 1]) {
4246 Jim_AppendStrings(goi->interp,
4247 Jim_GetResult(goi->interp),
4248 target_types[x]->name,
4251 Jim_AppendStrings(goi->interp,
4252 Jim_GetResult(goi->interp),
4254 target_types[x]->name,NULL);
4261 target = calloc(1,sizeof(target_t));
4262 /* set target number */
4263 target->target_number = new_target_number();
4265 /* allocate memory for each unique target type */
4266 target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4268 memcpy(target->type, target_types[x], sizeof(target_type_t));
4270 /* will be set by "-endian" */
4271 target->endianness = TARGET_ENDIAN_UNKNOWN;
4273 target->working_area = 0x0;
4274 target->working_area_size = 0x0;
4275 target->working_areas = NULL;
4276 target->backup_working_area = 0;
4278 target->state = TARGET_UNKNOWN;
4279 target->debug_reason = DBG_REASON_UNDEFINED;
4280 target->reg_cache = NULL;
4281 target->breakpoints = NULL;
4282 target->watchpoints = NULL;
4283 target->next = NULL;
4284 target->arch_info = NULL;
4286 target->display = 1;
4288 target->halt_issued = false;
4290 /* initialize trace information */
4291 target->trace_info = malloc(sizeof(trace_t));
4292 target->trace_info->num_trace_points = 0;
4293 target->trace_info->trace_points_size = 0;
4294 target->trace_info->trace_points = NULL;
4295 target->trace_info->trace_history_size = 0;
4296 target->trace_info->trace_history = NULL;
4297 target->trace_info->trace_history_pos = 0;
4298 target->trace_info->trace_history_overflowed = 0;
4300 target->dbgmsg = NULL;
4301 target->dbg_msg_enabled = 0;
4303 target->endianness = TARGET_ENDIAN_UNKNOWN;
4305 /* Do the rest as "configure" options */
4306 goi->isconfigure = 1;
4307 e = target_configure(goi, target);
4309 if (target->tap == NULL)
4311 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4321 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4322 /* default endian to little if not specified */
4323 target->endianness = TARGET_LITTLE_ENDIAN;
4326 /* incase variant is not set */
4327 if (!target->variant)
4328 target->variant = strdup("");
4330 /* create the target specific commands */
4331 if (target->type->register_commands) {
4332 (*(target->type->register_commands))(cmd_ctx);
4334 if (target->type->target_create) {
4335 (*(target->type->target_create))(target, goi->interp);
4338 /* append to end of list */
4341 tpp = &(all_targets);
4343 tpp = &((*tpp)->next);
4348 cp = Jim_GetString(new_cmd, NULL);
4349 target->cmd_name = strdup(cp);
4351 /* now - create the new target name command */
4352 e = Jim_CreateCommand(goi->interp,
4355 tcl_target_func, /* C function */
4356 target, /* private data */
4357 NULL); /* no del proc */
4362 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4366 struct command_context_s *cmd_ctx;
4370 /* TG = target generic */
4378 const char *target_cmds[] = {
4379 "create", "types", "names", "current", "number",
4381 NULL /* terminate */
4384 LOG_DEBUG("Target command params:");
4385 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4387 cmd_ctx = Jim_GetAssocData(interp, "context");
4389 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4391 if (goi.argc == 0) {
4392 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4396 /* Jim_GetOpt_Debug(&goi); */
4397 r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4404 Jim_Panic(goi.interp,"Why am I here?");
4406 case TG_CMD_CURRENT:
4407 if (goi.argc != 0) {
4408 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4411 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4414 if (goi.argc != 0) {
4415 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4418 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4419 for (x = 0 ; target_types[x] ; x++) {
4420 Jim_ListAppendElement(goi.interp,
4421 Jim_GetResult(goi.interp),
4422 Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4426 if (goi.argc != 0) {
4427 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4430 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4431 target = all_targets;
4433 Jim_ListAppendElement(goi.interp,
4434 Jim_GetResult(goi.interp),
4435 Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4436 target = target->next;
4441 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4444 return target_create(&goi);
4447 /* It's OK to remove this mechanism sometime after August 2010 or so */
4448 LOG_WARNING("don't use numbers as target identifiers; use names");
4449 if (goi.argc != 1) {
4450 Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4453 e = Jim_GetOpt_Wide(&goi, &w);
4457 for (x = 0, target = all_targets; target; target = target->next, x++) {
4458 if (target->target_number == w)
4461 if (target == NULL) {
4462 Jim_SetResult_sprintf(goi.interp,
4463 "Target: number %d does not exist", (int)(w));
4466 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4469 if (goi.argc != 0) {
4470 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4473 for (x = 0, target = all_targets; target; target = target->next, x++)
4475 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4491 static int fastload_num;
4492 static struct FastLoad *fastload;
4494 static void free_fastload(void)
4496 if (fastload != NULL)
4499 for (i = 0; i < fastload_num; i++)
4501 if (fastload[i].data)
4502 free(fastload[i].data);
4512 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4516 uint32_t image_size;
4517 uint32_t min_address = 0;
4518 uint32_t max_address = 0xffffffff;
4523 int retval = parse_load_image_command_args(cmd_ctx, args, argc,
4524 &image, &min_address, &max_address);
4525 if (ERROR_OK != retval)
4528 struct duration bench;
4529 duration_start(&bench);
4531 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4538 fastload_num = image.num_sections;
4539 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4540 if (fastload == NULL)
4542 image_close(&image);
4545 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4546 for (i = 0; i < image.num_sections; i++)
4548 buffer = malloc(image.sections[i].size);
4551 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4552 (int)(image.sections[i].size));
4556 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4562 uint32_t offset = 0;
4563 uint32_t length = buf_cnt;
4566 /* DANGER!!! beware of unsigned comparision here!!! */
4568 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4569 (image.sections[i].base_address < max_address))
4571 if (image.sections[i].base_address < min_address)
4573 /* clip addresses below */
4574 offset += min_address-image.sections[i].base_address;
4578 if (image.sections[i].base_address + buf_cnt > max_address)
4580 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4583 fastload[i].address = image.sections[i].base_address + offset;
4584 fastload[i].data = malloc(length);
4585 if (fastload[i].data == NULL)
4590 memcpy(fastload[i].data, buffer + offset, length);
4591 fastload[i].length = length;
4593 image_size += length;
4594 command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4595 (unsigned int)length,
4596 ((unsigned int)(image.sections[i].base_address + offset)));
4602 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4604 command_print(cmd_ctx, "Loaded %" PRIu32 " bytes "
4605 "in %fs (%0.3f kb/s)", image_size,
4606 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4608 command_print(cmd_ctx,
4609 "WARNING: image has not been loaded to target!"
4610 "You can issue a 'fast_load' to finish loading.");
4613 image_close(&image);
4615 if (retval != ERROR_OK)
4623 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4626 return ERROR_COMMAND_SYNTAX_ERROR;
4627 if (fastload == NULL)
4629 LOG_ERROR("No image in memory");
4633 int ms = timeval_ms();
4635 int retval = ERROR_OK;
4636 for (i = 0; i < fastload_num;i++)
4638 target_t *target = get_current_target(cmd_ctx);
4639 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4640 (unsigned int)(fastload[i].address),
4641 (unsigned int)(fastload[i].length));
4642 if (retval == ERROR_OK)
4644 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4646 size += fastload[i].length;
4648 int after = timeval_ms();
4649 command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4653 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4655 command_context_t *context;
4659 context = Jim_GetAssocData(interp, "context");
4660 if (context == NULL) {
4661 LOG_ERROR("array2mem: no command context");
4664 target = get_current_target(context);
4665 if (target == NULL) {
4666 LOG_ERROR("array2mem: no current target");
4670 if ((argc < 6) || (argc > 7))
4684 e = Jim_GetLong(interp, argv[1], &l);
4690 e = Jim_GetLong(interp, argv[2], &l);
4696 e = Jim_GetLong(interp, argv[3], &l);
4702 e = Jim_GetLong(interp, argv[4], &l);
4708 e = Jim_GetLong(interp, argv[5], &l);
4718 e = Jim_GetLong(interp, argv[6], &l);
4724 retval = target_mcr(target, cpnum, op1, op2, CRn, CRm, value);
4725 if (retval != ERROR_OK)
4729 retval = target_mrc(target, cpnum, op1, op2, CRn, CRm, &value);
4730 if (retval != ERROR_OK)
4733 Jim_SetResult(interp, Jim_NewIntObj(interp, value));
4739 int target_register_commands(struct command_context_s *cmd_ctx)
4742 register_command(cmd_ctx, NULL, "targets",
4743 handle_targets_command, COMMAND_EXEC,
4744 "change current command line target (one parameter) "
4745 "or list targets (no parameters)");
4747 register_jim(cmd_ctx, "target", jim_target, "configure target");
4752 int target_register_user_commands(struct command_context_s *cmd_ctx)
4754 int retval = ERROR_OK;
4755 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
4758 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
4761 register_command(cmd_ctx, NULL, "profile",
4762 handle_profile_command, COMMAND_EXEC,
4763 "profiling samples the CPU PC");
4765 register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array,
4766 "read memory and return as a TCL array for script processing "
4767 "<ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
4769 register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem,
4770 "convert a TCL array to memory locations and write the values "
4771 "<ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
4773 register_command(cmd_ctx, NULL, "fast_load_image",
4774 handle_fast_load_image_command, COMMAND_ANY,
4775 "same args as load_image, image stored in memory "
4776 "- mainly for profiling purposes");
4778 register_command(cmd_ctx, NULL, "fast_load",
4779 handle_fast_load_command, COMMAND_ANY,
4780 "loads active fast load image to current target "
4781 "- mainly for profiling purposes");
4784 register_command(cmd_ctx, NULL, "virt2phys",
4785 handle_virt2phys_command, COMMAND_ANY,
4786 "translate a virtual address into a physical address");
4787 register_command(cmd_ctx, NULL, "reg",
4788 handle_reg_command, COMMAND_EXEC,
4789 "display or set a register");
4791 register_command(cmd_ctx, NULL, "poll",
4792 handle_poll_command, COMMAND_EXEC,
4793 "poll target state");
4794 register_command(cmd_ctx, NULL, "wait_halt",
4795 handle_wait_halt_command, COMMAND_EXEC,
4796 "wait for target halt [time (s)]");
4797 register_command(cmd_ctx, NULL, "halt",
4798 handle_halt_command, COMMAND_EXEC,
4800 register_command(cmd_ctx, NULL, "resume",
4801 handle_resume_command, COMMAND_EXEC,
4802 "resume target [addr]");
4803 register_command(cmd_ctx, NULL, "reset",
4804 handle_reset_command, COMMAND_EXEC,
4805 "reset target [run | halt | init] - default is run");
4806 register_command(cmd_ctx, NULL, "soft_reset_halt",
4807 handle_soft_reset_halt_command, COMMAND_EXEC,
4808 "halt the target and do a soft reset");
4810 register_command(cmd_ctx, NULL, "step",
4811 handle_step_command, COMMAND_EXEC,
4812 "step one instruction from current PC or [addr]");
4814 register_command(cmd_ctx, NULL, "mdw",
4815 handle_md_command, COMMAND_EXEC,
4816 "display memory words [phys] <addr> [count]");
4817 register_command(cmd_ctx, NULL, "mdh",
4818 handle_md_command, COMMAND_EXEC,
4819 "display memory half-words [phys] <addr> [count]");
4820 register_command(cmd_ctx, NULL, "mdb",
4821 handle_md_command, COMMAND_EXEC,
4822 "display memory bytes [phys] <addr> [count]");
4824 register_command(cmd_ctx, NULL, "mww",
4825 handle_mw_command, COMMAND_EXEC,
4826 "write memory word [phys] <addr> <value> [count]");
4827 register_command(cmd_ctx, NULL, "mwh",
4828 handle_mw_command, COMMAND_EXEC,
4829 "write memory half-word [phys] <addr> <value> [count]");
4830 register_command(cmd_ctx, NULL, "mwb",
4831 handle_mw_command, COMMAND_EXEC,
4832 "write memory byte [phys] <addr> <value> [count]");
4834 register_command(cmd_ctx, NULL, "bp",
4835 handle_bp_command, COMMAND_EXEC,
4836 "list or set breakpoint [<address> <length> [hw]]");
4837 register_command(cmd_ctx, NULL, "rbp",
4838 handle_rbp_command, COMMAND_EXEC,
4839 "remove breakpoint <address>");
4841 register_command(cmd_ctx, NULL, "wp",
4842 handle_wp_command, COMMAND_EXEC,
4843 "list or set watchpoint "
4844 "[<address> <length> <r/w/a> [value] [mask]]");
4845 register_command(cmd_ctx, NULL, "rwp",
4846 handle_rwp_command, COMMAND_EXEC,
4847 "remove watchpoint <address>");
4849 register_command(cmd_ctx, NULL, "load_image",
4850 handle_load_image_command, COMMAND_EXEC,
4851 "load_image <file> <address> "
4852 "['bin'|'ihex'|'elf'|'s19'] [min_address] [max_length]");
4853 register_command(cmd_ctx, NULL, "dump_image",
4854 handle_dump_image_command, COMMAND_EXEC,
4855 "dump_image <file> <address> <size>");
4856 register_command(cmd_ctx, NULL, "verify_image",
4857 handle_verify_image_command, COMMAND_EXEC,
4858 "verify_image <file> [offset] [type]");
4859 register_command(cmd_ctx, NULL, "test_image",
4860 handle_test_image_command, COMMAND_EXEC,
4861 "test_image <file> [offset] [type]");