Added target_read/write_phys_memory() fn's. mdX/mwX commands updated to support phys...
[openocd/ztw.git] / src / target / target.c
blob45162070183de1b659bbf3a7160c361e0a21f3a5
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2009 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
10 * *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
13 * *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
16 * *
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. *
21 * *
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. *
26 * *
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 ***************************************************************************/
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
36 #include "target.h"
37 #include "target_type.h"
38 #include "target_request.h"
39 #include "time_support.h"
40 #include "register.h"
41 #include "trace.h"
42 #include "image.h"
43 #include "jtag.h"
46 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
48 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
49 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
50 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
51 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
52 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
53 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
54 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
55 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
56 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
57 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
58 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
59 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
60 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
61 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
62 static int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
63 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
64 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
65 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
66 static int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc);
67 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
68 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
69 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
71 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
72 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
73 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
75 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
76 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
78 /* targets */
79 extern target_type_t arm7tdmi_target;
80 extern target_type_t arm720t_target;
81 extern target_type_t arm9tdmi_target;
82 extern target_type_t arm920t_target;
83 extern target_type_t arm966e_target;
84 extern target_type_t arm926ejs_target;
85 extern target_type_t fa526_target;
86 extern target_type_t feroceon_target;
87 extern target_type_t dragonite_target;
88 extern target_type_t xscale_target;
89 extern target_type_t cortexm3_target;
90 extern target_type_t cortexa8_target;
91 extern target_type_t arm11_target;
92 extern target_type_t mips_m4k_target;
93 extern target_type_t avr_target;
95 target_type_t *target_types[] =
97 &arm7tdmi_target,
98 &arm9tdmi_target,
99 &arm920t_target,
100 &arm720t_target,
101 &arm966e_target,
102 &arm926ejs_target,
103 &fa526_target,
104 &feroceon_target,
105 &dragonite_target,
106 &xscale_target,
107 &cortexm3_target,
108 &cortexa8_target,
109 &arm11_target,
110 &mips_m4k_target,
111 &avr_target,
112 NULL,
115 target_t *all_targets = NULL;
116 target_event_callback_t *target_event_callbacks = NULL;
117 target_timer_callback_t *target_timer_callbacks = NULL;
119 const Jim_Nvp nvp_assert[] = {
120 { .name = "assert", NVP_ASSERT },
121 { .name = "deassert", NVP_DEASSERT },
122 { .name = "T", NVP_ASSERT },
123 { .name = "F", NVP_DEASSERT },
124 { .name = "t", NVP_ASSERT },
125 { .name = "f", NVP_DEASSERT },
126 { .name = NULL, .value = -1 }
129 const Jim_Nvp nvp_error_target[] = {
130 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
131 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
132 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
133 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
134 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
135 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
136 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
137 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
138 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
139 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
140 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
141 { .value = -1, .name = NULL }
144 const char *target_strerror_safe(int err)
146 const Jim_Nvp *n;
148 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
149 if (n->name == NULL) {
150 return "unknown";
151 } else {
152 return n->name;
156 static const Jim_Nvp nvp_target_event[] = {
157 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
158 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
160 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
161 { .value = TARGET_EVENT_HALTED, .name = "halted" },
162 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
163 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
164 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
166 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
167 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
169 /* historical name */
171 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
173 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
174 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
175 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
176 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
177 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
178 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
179 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
180 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
181 { .value = TARGET_EVENT_RESET_INIT , .name = "reset-init" },
182 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
184 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
185 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
187 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
188 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
190 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
191 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
193 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
194 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
196 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
197 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
199 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
200 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
201 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
203 { .name = NULL, .value = -1 }
206 const Jim_Nvp nvp_target_state[] = {
207 { .name = "unknown", .value = TARGET_UNKNOWN },
208 { .name = "running", .value = TARGET_RUNNING },
209 { .name = "halted", .value = TARGET_HALTED },
210 { .name = "reset", .value = TARGET_RESET },
211 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
212 { .name = NULL, .value = -1 },
215 const Jim_Nvp nvp_target_debug_reason [] = {
216 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
217 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
218 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
219 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
220 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
221 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
222 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
223 { .name = NULL, .value = -1 },
226 const Jim_Nvp nvp_target_endian[] = {
227 { .name = "big", .value = TARGET_BIG_ENDIAN },
228 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
229 { .name = "be", .value = TARGET_BIG_ENDIAN },
230 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
231 { .name = NULL, .value = -1 },
234 const Jim_Nvp nvp_reset_modes[] = {
235 { .name = "unknown", .value = RESET_UNKNOWN },
236 { .name = "run" , .value = RESET_RUN },
237 { .name = "halt" , .value = RESET_HALT },
238 { .name = "init" , .value = RESET_INIT },
239 { .name = NULL , .value = -1 },
242 const char *
243 target_state_name( target_t *t )
245 const char *cp;
246 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
247 if( !cp ){
248 LOG_ERROR("Invalid target state: %d", (int)(t->state));
249 cp = "(*BUG*unknown*BUG*)";
251 return cp;
254 /* determine the number of the new target */
255 static int new_target_number(void)
257 target_t *t;
258 int x;
260 /* number is 0 based */
261 x = -1;
262 t = all_targets;
263 while (t) {
264 if (x < t->target_number) {
265 x = t->target_number;
267 t = t->next;
269 return x + 1;
272 /* read a uint32_t from a buffer in target memory endianness */
273 uint32_t target_buffer_get_u32(target_t *target, const uint8_t *buffer)
275 if (target->endianness == TARGET_LITTLE_ENDIAN)
276 return le_to_h_u32(buffer);
277 else
278 return be_to_h_u32(buffer);
281 /* read a uint16_t from a buffer in target memory endianness */
282 uint16_t target_buffer_get_u16(target_t *target, const uint8_t *buffer)
284 if (target->endianness == TARGET_LITTLE_ENDIAN)
285 return le_to_h_u16(buffer);
286 else
287 return be_to_h_u16(buffer);
290 /* read a uint8_t from a buffer in target memory endianness */
291 uint8_t target_buffer_get_u8(target_t *target, const uint8_t *buffer)
293 return *buffer & 0x0ff;
296 /* write a uint32_t to a buffer in target memory endianness */
297 void target_buffer_set_u32(target_t *target, uint8_t *buffer, uint32_t value)
299 if (target->endianness == TARGET_LITTLE_ENDIAN)
300 h_u32_to_le(buffer, value);
301 else
302 h_u32_to_be(buffer, value);
305 /* write a uint16_t to a buffer in target memory endianness */
306 void target_buffer_set_u16(target_t *target, uint8_t *buffer, uint16_t value)
308 if (target->endianness == TARGET_LITTLE_ENDIAN)
309 h_u16_to_le(buffer, value);
310 else
311 h_u16_to_be(buffer, value);
314 /* write a uint8_t to a buffer in target memory endianness */
315 void target_buffer_set_u8(target_t *target, uint8_t *buffer, uint8_t value)
317 *buffer = value;
320 /* return a pointer to a configured target; id is name or number */
321 target_t *get_target(const char *id)
323 target_t *target;
325 /* try as tcltarget name */
326 for (target = all_targets; target; target = target->next) {
327 if (target->cmd_name == NULL)
328 continue;
329 if (strcmp(id, target->cmd_name) == 0)
330 return target;
333 /* It's OK to remove this fallback sometime after August 2010 or so */
335 /* no match, try as number */
336 unsigned num;
337 if (parse_uint(id, &num) != ERROR_OK)
338 return NULL;
340 for (target = all_targets; target; target = target->next) {
341 if (target->target_number == (int)num) {
342 LOG_WARNING("use '%s' as target identifier, not '%u'",
343 target->cmd_name, num);
344 return target;
348 return NULL;
351 /* returns a pointer to the n-th configured target */
352 static target_t *get_target_by_num(int num)
354 target_t *target = all_targets;
356 while (target) {
357 if (target->target_number == num) {
358 return target;
360 target = target->next;
363 return NULL;
366 target_t* get_current_target(command_context_t *cmd_ctx)
368 target_t *target = get_target_by_num(cmd_ctx->current_target);
370 if (target == NULL)
372 LOG_ERROR("BUG: current_target out of bounds");
373 exit(-1);
376 return target;
379 int target_poll(struct target_s *target)
381 int retval;
383 /* We can't poll until after examine */
384 if (!target_was_examined(target))
386 /* Fail silently lest we pollute the log */
387 return ERROR_FAIL;
390 retval = target->type->poll(target);
391 if (retval != ERROR_OK)
392 return retval;
394 if (target->halt_issued)
396 if (target->state == TARGET_HALTED)
398 target->halt_issued = false;
399 } else
401 long long t = timeval_ms() - target->halt_issued_time;
402 if (t>1000)
404 target->halt_issued = false;
405 LOG_INFO("Halt timed out, wake up GDB.");
406 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
411 return ERROR_OK;
414 int target_halt(struct target_s *target)
416 int retval;
417 /* We can't poll until after examine */
418 if (!target_was_examined(target))
420 LOG_ERROR("Target not examined yet");
421 return ERROR_FAIL;
424 retval = target->type->halt(target);
425 if (retval != ERROR_OK)
426 return retval;
428 target->halt_issued = true;
429 target->halt_issued_time = timeval_ms();
431 return ERROR_OK;
434 int target_resume(struct target_s *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
436 int retval;
438 /* We can't poll until after examine */
439 if (!target_was_examined(target))
441 LOG_ERROR("Target not examined yet");
442 return ERROR_FAIL;
445 /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
446 * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
447 * the application.
449 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
450 return retval;
452 return retval;
455 int target_process_reset(struct command_context_s *cmd_ctx, enum target_reset_mode reset_mode)
457 char buf[100];
458 int retval;
459 Jim_Nvp *n;
460 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
461 if (n->name == NULL) {
462 LOG_ERROR("invalid reset mode");
463 return ERROR_FAIL;
466 /* disable polling during reset to make reset event scripts
467 * more predictable, i.e. dr/irscan & pathmove in events will
468 * not have JTAG operations injected into the middle of a sequence.
470 bool save_poll = jtag_poll_get_enabled();
472 jtag_poll_set_enabled(false);
474 sprintf(buf, "ocd_process_reset %s", n->name);
475 retval = Jim_Eval(interp, buf);
477 jtag_poll_set_enabled(save_poll);
479 if (retval != JIM_OK) {
480 Jim_PrintErrorMessage(interp);
481 return ERROR_FAIL;
484 /* We want any events to be processed before the prompt */
485 retval = target_call_timer_callbacks_now();
487 return retval;
490 static int default_virt2phys(struct target_s *target, uint32_t virtual, uint32_t *physical)
492 *physical = virtual;
493 return ERROR_OK;
496 static int default_mmu(struct target_s *target, int *enabled)
498 *enabled = 0;
499 return ERROR_OK;
502 static int default_examine(struct target_s *target)
504 target_set_examined(target);
505 return ERROR_OK;
508 int target_examine_one(struct target_s *target)
510 return target->type->examine(target);
513 static int jtag_enable_callback(enum jtag_event event, void *priv)
515 target_t *target = priv;
517 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
518 return ERROR_OK;
520 jtag_unregister_event_callback(jtag_enable_callback, target);
521 return target_examine_one(target);
525 /* Targets that correctly implement init + examine, i.e.
526 * no communication with target during init:
528 * XScale
530 int target_examine(void)
532 int retval = ERROR_OK;
533 target_t *target;
535 for (target = all_targets; target; target = target->next)
537 /* defer examination, but don't skip it */
538 if (!target->tap->enabled) {
539 jtag_register_event_callback(jtag_enable_callback,
540 target);
541 continue;
543 if ((retval = target_examine_one(target)) != ERROR_OK)
544 return retval;
546 return retval;
548 const char *target_get_name(struct target_s *target)
550 return target->type->name;
553 static int target_write_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
555 if (!target_was_examined(target))
557 LOG_ERROR("Target not examined yet");
558 return ERROR_FAIL;
560 return target->type->write_memory_imp(target, address, size, count, buffer);
563 static int target_read_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
565 if (!target_was_examined(target))
567 LOG_ERROR("Target not examined yet");
568 return ERROR_FAIL;
570 return target->type->read_memory_imp(target, address, size, count, buffer);
573 static int target_soft_reset_halt_imp(struct target_s *target)
575 if (!target_was_examined(target))
577 LOG_ERROR("Target not examined yet");
578 return ERROR_FAIL;
580 if (!target->type->soft_reset_halt_imp) {
581 LOG_ERROR("Target %s does not support soft_reset_halt",
582 target->cmd_name);
583 return ERROR_FAIL;
585 return target->type->soft_reset_halt_imp(target);
588 static int target_run_algorithm_imp(struct target_s *target, int num_mem_params, mem_param_t *mem_params, int num_reg_params, reg_param_t *reg_param, uint32_t entry_point, uint32_t exit_point, int timeout_ms, void *arch_info)
590 if (!target_was_examined(target))
592 LOG_ERROR("Target not examined yet");
593 return ERROR_FAIL;
595 return target->type->run_algorithm_imp(target, num_mem_params, mem_params, num_reg_params, reg_param, entry_point, exit_point, timeout_ms, arch_info);
598 int target_read_memory(struct target_s *target,
599 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
601 return target->type->read_memory(target, address, size, count, buffer);
604 int target_read_phys_memory(struct target_s *target,
605 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
607 return target->type->read_phys_memory(target, address, size, count, buffer);
610 int target_write_memory(struct target_s *target,
611 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
613 return target->type->write_memory(target, address, size, count, buffer);
616 int target_write_phys_memory(struct target_s *target,
617 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
619 return target->type->write_phys_memory(target, address, size, count, buffer);
622 int target_bulk_write_memory(struct target_s *target,
623 uint32_t address, uint32_t count, uint8_t *buffer)
625 return target->type->bulk_write_memory(target, address, count, buffer);
628 int target_add_breakpoint(struct target_s *target,
629 struct breakpoint_s *breakpoint)
631 return target->type->add_breakpoint(target, breakpoint);
633 int target_remove_breakpoint(struct target_s *target,
634 struct breakpoint_s *breakpoint)
636 return target->type->remove_breakpoint(target, breakpoint);
639 int target_add_watchpoint(struct target_s *target,
640 struct watchpoint_s *watchpoint)
642 return target->type->add_watchpoint(target, watchpoint);
644 int target_remove_watchpoint(struct target_s *target,
645 struct watchpoint_s *watchpoint)
647 return target->type->remove_watchpoint(target, watchpoint);
650 int target_get_gdb_reg_list(struct target_s *target,
651 struct reg_s **reg_list[], int *reg_list_size)
653 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
655 int target_step(struct target_s *target,
656 int current, uint32_t address, int handle_breakpoints)
658 return target->type->step(target, current, address, handle_breakpoints);
662 int target_run_algorithm(struct target_s *target,
663 int num_mem_params, mem_param_t *mem_params,
664 int num_reg_params, reg_param_t *reg_param,
665 uint32_t entry_point, uint32_t exit_point,
666 int timeout_ms, void *arch_info)
668 return target->type->run_algorithm(target,
669 num_mem_params, mem_params, num_reg_params, reg_param,
670 entry_point, exit_point, timeout_ms, arch_info);
673 /// @returns @c true if the target has been examined.
674 bool target_was_examined(struct target_s *target)
676 return target->type->examined;
678 /// Sets the @c examined flag for the given target.
679 void target_set_examined(struct target_s *target)
681 target->type->examined = true;
683 // Reset the @c examined flag for the given target.
684 void target_reset_examined(struct target_s *target)
686 target->type->examined = false;
690 int target_init(struct command_context_s *cmd_ctx)
692 target_t *target = all_targets;
693 int retval;
695 while (target)
697 target_reset_examined(target);
698 if (target->type->examine == NULL)
700 target->type->examine = default_examine;
703 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
705 LOG_ERROR("target '%s' init failed", target_get_name(target));
706 return retval;
709 /* Set up default functions if none are provided by target */
710 if (target->type->virt2phys == NULL)
712 target->type->virt2phys = default_virt2phys;
715 if (target->type->read_phys_memory == NULL)
717 target->type->read_phys_memory = target->type->read_memory;
720 if (target->type->write_phys_memory == NULL)
722 target->type->write_phys_memory = target->type->write_memory;
725 /* a non-invasive way(in terms of patches) to add some code that
726 * runs before the type->write/read_memory implementation
728 target->type->write_memory_imp = target->type->write_memory;
729 target->type->write_memory = target_write_memory_imp;
730 target->type->read_memory_imp = target->type->read_memory;
731 target->type->read_memory = target_read_memory_imp;
732 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
733 target->type->soft_reset_halt = target_soft_reset_halt_imp;
734 target->type->run_algorithm_imp = target->type->run_algorithm;
735 target->type->run_algorithm = target_run_algorithm_imp;
737 if (target->type->mmu == NULL)
739 target->type->mmu = default_mmu;
741 target = target->next;
744 if (all_targets)
746 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
747 return retval;
748 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
749 return retval;
752 return ERROR_OK;
755 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
757 target_event_callback_t **callbacks_p = &target_event_callbacks;
759 if (callback == NULL)
761 return ERROR_INVALID_ARGUMENTS;
764 if (*callbacks_p)
766 while ((*callbacks_p)->next)
767 callbacks_p = &((*callbacks_p)->next);
768 callbacks_p = &((*callbacks_p)->next);
771 (*callbacks_p) = malloc(sizeof(target_event_callback_t));
772 (*callbacks_p)->callback = callback;
773 (*callbacks_p)->priv = priv;
774 (*callbacks_p)->next = NULL;
776 return ERROR_OK;
779 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
781 target_timer_callback_t **callbacks_p = &target_timer_callbacks;
782 struct timeval now;
784 if (callback == NULL)
786 return ERROR_INVALID_ARGUMENTS;
789 if (*callbacks_p)
791 while ((*callbacks_p)->next)
792 callbacks_p = &((*callbacks_p)->next);
793 callbacks_p = &((*callbacks_p)->next);
796 (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
797 (*callbacks_p)->callback = callback;
798 (*callbacks_p)->periodic = periodic;
799 (*callbacks_p)->time_ms = time_ms;
801 gettimeofday(&now, NULL);
802 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
803 time_ms -= (time_ms % 1000);
804 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
805 if ((*callbacks_p)->when.tv_usec > 1000000)
807 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
808 (*callbacks_p)->when.tv_sec += 1;
811 (*callbacks_p)->priv = priv;
812 (*callbacks_p)->next = NULL;
814 return ERROR_OK;
817 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
819 target_event_callback_t **p = &target_event_callbacks;
820 target_event_callback_t *c = target_event_callbacks;
822 if (callback == NULL)
824 return ERROR_INVALID_ARGUMENTS;
827 while (c)
829 target_event_callback_t *next = c->next;
830 if ((c->callback == callback) && (c->priv == priv))
832 *p = next;
833 free(c);
834 return ERROR_OK;
836 else
837 p = &(c->next);
838 c = next;
841 return ERROR_OK;
844 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
846 target_timer_callback_t **p = &target_timer_callbacks;
847 target_timer_callback_t *c = target_timer_callbacks;
849 if (callback == NULL)
851 return ERROR_INVALID_ARGUMENTS;
854 while (c)
856 target_timer_callback_t *next = c->next;
857 if ((c->callback == callback) && (c->priv == priv))
859 *p = next;
860 free(c);
861 return ERROR_OK;
863 else
864 p = &(c->next);
865 c = next;
868 return ERROR_OK;
871 int target_call_event_callbacks(target_t *target, enum target_event event)
873 target_event_callback_t *callback = target_event_callbacks;
874 target_event_callback_t *next_callback;
876 if (event == TARGET_EVENT_HALTED)
878 /* execute early halted first */
879 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
882 LOG_DEBUG("target event %i (%s)",
883 event,
884 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
886 target_handle_event(target, event);
888 while (callback)
890 next_callback = callback->next;
891 callback->callback(target, event, callback->priv);
892 callback = next_callback;
895 return ERROR_OK;
898 static int target_timer_callback_periodic_restart(
899 target_timer_callback_t *cb, struct timeval *now)
901 int time_ms = cb->time_ms;
902 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
903 time_ms -= (time_ms % 1000);
904 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
905 if (cb->when.tv_usec > 1000000)
907 cb->when.tv_usec = cb->when.tv_usec - 1000000;
908 cb->when.tv_sec += 1;
910 return ERROR_OK;
913 static int target_call_timer_callback(target_timer_callback_t *cb,
914 struct timeval *now)
916 cb->callback(cb->priv);
918 if (cb->periodic)
919 return target_timer_callback_periodic_restart(cb, now);
921 return target_unregister_timer_callback(cb->callback, cb->priv);
924 static int target_call_timer_callbacks_check_time(int checktime)
926 keep_alive();
928 struct timeval now;
929 gettimeofday(&now, NULL);
931 target_timer_callback_t *callback = target_timer_callbacks;
932 while (callback)
934 // cleaning up may unregister and free this callback
935 target_timer_callback_t *next_callback = callback->next;
937 bool call_it = callback->callback &&
938 ((!checktime && callback->periodic) ||
939 now.tv_sec > callback->when.tv_sec ||
940 (now.tv_sec == callback->when.tv_sec &&
941 now.tv_usec >= callback->when.tv_usec));
943 if (call_it)
945 int retval = target_call_timer_callback(callback, &now);
946 if (retval != ERROR_OK)
947 return retval;
950 callback = next_callback;
953 return ERROR_OK;
956 int target_call_timer_callbacks(void)
958 return target_call_timer_callbacks_check_time(1);
961 /* invoke periodic callbacks immediately */
962 int target_call_timer_callbacks_now(void)
964 return target_call_timer_callbacks_check_time(0);
967 int target_alloc_working_area(struct target_s *target, uint32_t size, working_area_t **area)
969 working_area_t *c = target->working_areas;
970 working_area_t *new_wa = NULL;
972 /* Reevaluate working area address based on MMU state*/
973 if (target->working_areas == NULL)
975 int retval;
976 int enabled;
977 retval = target->type->mmu(target, &enabled);
978 if (retval != ERROR_OK)
980 return retval;
982 if (enabled)
984 target->working_area = target->working_area_virt;
986 else
988 target->working_area = target->working_area_phys;
992 /* only allocate multiples of 4 byte */
993 if (size % 4)
995 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
996 size = (size + 3) & (~3);
999 /* see if there's already a matching working area */
1000 while (c)
1002 if ((c->free) && (c->size == size))
1004 new_wa = c;
1005 break;
1007 c = c->next;
1010 /* if not, allocate a new one */
1011 if (!new_wa)
1013 working_area_t **p = &target->working_areas;
1014 uint32_t first_free = target->working_area;
1015 uint32_t free_size = target->working_area_size;
1017 LOG_DEBUG("allocating new working area");
1019 c = target->working_areas;
1020 while (c)
1022 first_free += c->size;
1023 free_size -= c->size;
1024 p = &c->next;
1025 c = c->next;
1028 if (free_size < size)
1030 LOG_WARNING("not enough working area available(requested %u, free %u)",
1031 (unsigned)(size), (unsigned)(free_size));
1032 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1035 new_wa = malloc(sizeof(working_area_t));
1036 new_wa->next = NULL;
1037 new_wa->size = size;
1038 new_wa->address = first_free;
1040 if (target->backup_working_area)
1042 int retval;
1043 new_wa->backup = malloc(new_wa->size);
1044 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1046 free(new_wa->backup);
1047 free(new_wa);
1048 return retval;
1051 else
1053 new_wa->backup = NULL;
1056 /* put new entry in list */
1057 *p = new_wa;
1060 /* mark as used, and return the new (reused) area */
1061 new_wa->free = 0;
1062 *area = new_wa;
1064 /* user pointer */
1065 new_wa->user = area;
1067 return ERROR_OK;
1070 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
1072 if (area->free)
1073 return ERROR_OK;
1075 if (restore && target->backup_working_area)
1077 int retval;
1078 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1079 return retval;
1082 area->free = 1;
1084 /* mark user pointer invalid */
1085 *area->user = NULL;
1086 area->user = NULL;
1088 return ERROR_OK;
1091 int target_free_working_area(struct target_s *target, working_area_t *area)
1093 return target_free_working_area_restore(target, area, 1);
1096 /* free resources and restore memory, if restoring memory fails,
1097 * free up resources anyway
1099 void target_free_all_working_areas_restore(struct target_s *target, int restore)
1101 working_area_t *c = target->working_areas;
1103 while (c)
1105 working_area_t *next = c->next;
1106 target_free_working_area_restore(target, c, restore);
1108 if (c->backup)
1109 free(c->backup);
1111 free(c);
1113 c = next;
1116 target->working_areas = NULL;
1119 void target_free_all_working_areas(struct target_s *target)
1121 target_free_all_working_areas_restore(target, 1);
1124 int target_register_commands(struct command_context_s *cmd_ctx)
1127 register_command(cmd_ctx, NULL, "targets", handle_targets_command, COMMAND_EXEC, "change the current command line target (one parameter) or lists targets (with no parameter)");
1132 register_jim(cmd_ctx, "target", jim_target, "configure target");
1134 return ERROR_OK;
1137 int target_arch_state(struct target_s *target)
1139 int retval;
1140 if (target == NULL)
1142 LOG_USER("No target has been configured");
1143 return ERROR_OK;
1146 LOG_USER("target state: %s", target_state_name( target ));
1148 if (target->state != TARGET_HALTED)
1149 return ERROR_OK;
1151 retval = target->type->arch_state(target);
1152 return retval;
1155 /* Single aligned words are guaranteed to use 16 or 32 bit access
1156 * mode respectively, otherwise data is handled as quickly as
1157 * possible
1159 int target_write_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1161 int retval;
1162 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1163 (int)size, (unsigned)address);
1165 if (!target_was_examined(target))
1167 LOG_ERROR("Target not examined yet");
1168 return ERROR_FAIL;
1171 if (size == 0) {
1172 return ERROR_OK;
1175 if ((address + size - 1) < address)
1177 /* GDB can request this when e.g. PC is 0xfffffffc*/
1178 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1179 (unsigned)address,
1180 (unsigned)size);
1181 return ERROR_FAIL;
1184 if (((address % 2) == 0) && (size == 2))
1186 return target_write_memory(target, address, 2, 1, buffer);
1189 /* handle unaligned head bytes */
1190 if (address % 4)
1192 uint32_t unaligned = 4 - (address % 4);
1194 if (unaligned > size)
1195 unaligned = size;
1197 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1198 return retval;
1200 buffer += unaligned;
1201 address += unaligned;
1202 size -= unaligned;
1205 /* handle aligned words */
1206 if (size >= 4)
1208 int aligned = size - (size % 4);
1210 /* use bulk writes above a certain limit. This may have to be changed */
1211 if (aligned > 128)
1213 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1214 return retval;
1216 else
1218 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1219 return retval;
1222 buffer += aligned;
1223 address += aligned;
1224 size -= aligned;
1227 /* handle tail writes of less than 4 bytes */
1228 if (size > 0)
1230 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1231 return retval;
1234 return ERROR_OK;
1237 /* Single aligned words are guaranteed to use 16 or 32 bit access
1238 * mode respectively, otherwise data is handled as quickly as
1239 * possible
1241 int target_read_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1243 int retval;
1244 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1245 (int)size, (unsigned)address);
1247 if (!target_was_examined(target))
1249 LOG_ERROR("Target not examined yet");
1250 return ERROR_FAIL;
1253 if (size == 0) {
1254 return ERROR_OK;
1257 if ((address + size - 1) < address)
1259 /* GDB can request this when e.g. PC is 0xfffffffc*/
1260 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1261 address,
1262 size);
1263 return ERROR_FAIL;
1266 if (((address % 2) == 0) && (size == 2))
1268 return target_read_memory(target, address, 2, 1, buffer);
1271 /* handle unaligned head bytes */
1272 if (address % 4)
1274 uint32_t unaligned = 4 - (address % 4);
1276 if (unaligned > size)
1277 unaligned = size;
1279 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1280 return retval;
1282 buffer += unaligned;
1283 address += unaligned;
1284 size -= unaligned;
1287 /* handle aligned words */
1288 if (size >= 4)
1290 int aligned = size - (size % 4);
1292 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1293 return retval;
1295 buffer += aligned;
1296 address += aligned;
1297 size -= aligned;
1300 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1301 if(size >=2)
1303 int aligned = size - (size%2);
1304 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1305 if (retval != ERROR_OK)
1306 return retval;
1308 buffer += aligned;
1309 address += aligned;
1310 size -= aligned;
1312 /* handle tail writes of less than 4 bytes */
1313 if (size > 0)
1315 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1316 return retval;
1319 return ERROR_OK;
1322 int target_checksum_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* crc)
1324 uint8_t *buffer;
1325 int retval;
1326 uint32_t i;
1327 uint32_t checksum = 0;
1328 if (!target_was_examined(target))
1330 LOG_ERROR("Target not examined yet");
1331 return ERROR_FAIL;
1334 if ((retval = target->type->checksum_memory(target, address,
1335 size, &checksum)) != ERROR_OK)
1337 buffer = malloc(size);
1338 if (buffer == NULL)
1340 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1341 return ERROR_INVALID_ARGUMENTS;
1343 retval = target_read_buffer(target, address, size, buffer);
1344 if (retval != ERROR_OK)
1346 free(buffer);
1347 return retval;
1350 /* convert to target endianess */
1351 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1353 uint32_t target_data;
1354 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1355 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1358 retval = image_calculate_checksum(buffer, size, &checksum);
1359 free(buffer);
1362 *crc = checksum;
1364 return retval;
1367 int target_blank_check_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* blank)
1369 int retval;
1370 if (!target_was_examined(target))
1372 LOG_ERROR("Target not examined yet");
1373 return ERROR_FAIL;
1376 if (target->type->blank_check_memory == 0)
1377 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1379 retval = target->type->blank_check_memory(target, address, size, blank);
1381 return retval;
1384 int target_read_u32(struct target_s *target, uint32_t address, uint32_t *value)
1386 uint8_t value_buf[4];
1387 if (!target_was_examined(target))
1389 LOG_ERROR("Target not examined yet");
1390 return ERROR_FAIL;
1393 int retval = target_read_memory(target, address, 4, 1, value_buf);
1395 if (retval == ERROR_OK)
1397 *value = target_buffer_get_u32(target, value_buf);
1398 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1399 address,
1400 *value);
1402 else
1404 *value = 0x0;
1405 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1406 address);
1409 return retval;
1412 int target_read_u16(struct target_s *target, uint32_t address, uint16_t *value)
1414 uint8_t value_buf[2];
1415 if (!target_was_examined(target))
1417 LOG_ERROR("Target not examined yet");
1418 return ERROR_FAIL;
1421 int retval = target_read_memory(target, address, 2, 1, value_buf);
1423 if (retval == ERROR_OK)
1425 *value = target_buffer_get_u16(target, value_buf);
1426 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1427 address,
1428 *value);
1430 else
1432 *value = 0x0;
1433 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1434 address);
1437 return retval;
1440 int target_read_u8(struct target_s *target, uint32_t address, uint8_t *value)
1442 int retval = target_read_memory(target, address, 1, 1, value);
1443 if (!target_was_examined(target))
1445 LOG_ERROR("Target not examined yet");
1446 return ERROR_FAIL;
1449 if (retval == ERROR_OK)
1451 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1452 address,
1453 *value);
1455 else
1457 *value = 0x0;
1458 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1459 address);
1462 return retval;
1465 int target_write_u32(struct target_s *target, uint32_t address, uint32_t value)
1467 int retval;
1468 uint8_t value_buf[4];
1469 if (!target_was_examined(target))
1471 LOG_ERROR("Target not examined yet");
1472 return ERROR_FAIL;
1475 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1476 address,
1477 value);
1479 target_buffer_set_u32(target, value_buf, value);
1480 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1482 LOG_DEBUG("failed: %i", retval);
1485 return retval;
1488 int target_write_u16(struct target_s *target, uint32_t address, uint16_t value)
1490 int retval;
1491 uint8_t value_buf[2];
1492 if (!target_was_examined(target))
1494 LOG_ERROR("Target not examined yet");
1495 return ERROR_FAIL;
1498 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1499 address,
1500 value);
1502 target_buffer_set_u16(target, value_buf, value);
1503 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1505 LOG_DEBUG("failed: %i", retval);
1508 return retval;
1511 int target_write_u8(struct target_s *target, uint32_t address, uint8_t value)
1513 int retval;
1514 if (!target_was_examined(target))
1516 LOG_ERROR("Target not examined yet");
1517 return ERROR_FAIL;
1520 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1521 address, value);
1523 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1525 LOG_DEBUG("failed: %i", retval);
1528 return retval;
1531 int target_register_user_commands(struct command_context_s *cmd_ctx)
1533 int retval = ERROR_OK;
1536 /* script procedures */
1537 register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "profiling samples the CPU PC");
1538 register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array, "read memory and return as a TCL array for script processing <ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
1539 register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem, "convert a TCL array to memory locations and write the values <ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
1541 register_command(cmd_ctx, NULL, "fast_load_image", handle_fast_load_image_command, COMMAND_ANY,
1542 "same args as load_image, image stored in memory - mainly for profiling purposes");
1544 register_command(cmd_ctx, NULL, "fast_load", handle_fast_load_command, COMMAND_ANY,
1545 "loads active fast load image to current target - mainly for profiling purposes");
1548 register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "translate a virtual address into a physical address");
1549 register_command(cmd_ctx, NULL, "reg", handle_reg_command, COMMAND_EXEC, "display or set a register");
1550 register_command(cmd_ctx, NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1551 register_command(cmd_ctx, NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1552 register_command(cmd_ctx, NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1553 register_command(cmd_ctx, NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1554 register_command(cmd_ctx, NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1555 register_command(cmd_ctx, NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run | halt | init] - default is run");
1556 register_command(cmd_ctx, NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1558 register_command(cmd_ctx, NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words [phys] <addr> [count]");
1559 register_command(cmd_ctx, NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words [phys] <addr> [count]");
1560 register_command(cmd_ctx, NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes [phys] <addr> [count]");
1562 register_command(cmd_ctx, NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word [phys] <addr> <value> [count]");
1563 register_command(cmd_ctx, NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word [phys] <addr> <value> [count]");
1564 register_command(cmd_ctx, NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte [phys] <addr> <value> [count]");
1566 register_command(cmd_ctx, NULL, "bp",
1567 handle_bp_command, COMMAND_EXEC,
1568 "list or set breakpoint [<address> <length> [hw]]");
1569 register_command(cmd_ctx, NULL, "rbp",
1570 handle_rbp_command, COMMAND_EXEC,
1571 "remove breakpoint <address>");
1572 register_command(cmd_ctx, NULL, "wp",
1573 handle_wp_command, COMMAND_EXEC,
1574 "list or set watchpoint "
1575 "[<address> <length> <r/w/a> [value] [mask]]");
1576 register_command(cmd_ctx, NULL, "rwp",
1577 handle_rwp_command, COMMAND_EXEC,
1578 "remove watchpoint <address>");
1580 register_command(cmd_ctx, NULL, "load_image", handle_load_image_command, COMMAND_EXEC, "load_image <file> <address> ['bin'|'ihex'|'elf'|'s19'] [min_address] [max_length]");
1581 register_command(cmd_ctx, NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1582 register_command(cmd_ctx, NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1583 register_command(cmd_ctx, NULL, "test_image", handle_test_image_command, COMMAND_EXEC, "test_image <file> [offset] [type]");
1585 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
1586 return retval;
1587 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
1588 return retval;
1590 return retval;
1593 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1595 target_t *target = all_targets;
1597 if (argc == 1)
1599 target = get_target(args[0]);
1600 if (target == NULL) {
1601 command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1602 goto DumpTargets;
1604 if (!target->tap->enabled) {
1605 command_print(cmd_ctx,"Target: TAP %s is disabled, "
1606 "can't be the current target\n",
1607 target->tap->dotted_name);
1608 return ERROR_FAIL;
1611 cmd_ctx->current_target = target->target_number;
1612 return ERROR_OK;
1614 DumpTargets:
1616 target = all_targets;
1617 command_print(cmd_ctx, " TargetName Type Endian TapName State ");
1618 command_print(cmd_ctx, "-- ------------------ ---------- ------ ------------------ ------------");
1619 while (target)
1621 const char *state;
1622 char marker = ' ';
1624 if (target->tap->enabled)
1625 state = target_state_name( target );
1626 else
1627 state = "tap-disabled";
1629 if (cmd_ctx->current_target == target->target_number)
1630 marker = '*';
1632 /* keep columns lined up to match the headers above */
1633 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1634 target->target_number,
1635 marker,
1636 target->cmd_name,
1637 target_get_name(target),
1638 Jim_Nvp_value2name_simple(nvp_target_endian,
1639 target->endianness)->name,
1640 target->tap->dotted_name,
1641 state);
1642 target = target->next;
1645 return ERROR_OK;
1648 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1650 static int powerDropout;
1651 static int srstAsserted;
1653 static int runPowerRestore;
1654 static int runPowerDropout;
1655 static int runSrstAsserted;
1656 static int runSrstDeasserted;
1658 static int sense_handler(void)
1660 static int prevSrstAsserted = 0;
1661 static int prevPowerdropout = 0;
1663 int retval;
1664 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1665 return retval;
1667 int powerRestored;
1668 powerRestored = prevPowerdropout && !powerDropout;
1669 if (powerRestored)
1671 runPowerRestore = 1;
1674 long long current = timeval_ms();
1675 static long long lastPower = 0;
1676 int waitMore = lastPower + 2000 > current;
1677 if (powerDropout && !waitMore)
1679 runPowerDropout = 1;
1680 lastPower = current;
1683 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1684 return retval;
1686 int srstDeasserted;
1687 srstDeasserted = prevSrstAsserted && !srstAsserted;
1689 static long long lastSrst = 0;
1690 waitMore = lastSrst + 2000 > current;
1691 if (srstDeasserted && !waitMore)
1693 runSrstDeasserted = 1;
1694 lastSrst = current;
1697 if (!prevSrstAsserted && srstAsserted)
1699 runSrstAsserted = 1;
1702 prevSrstAsserted = srstAsserted;
1703 prevPowerdropout = powerDropout;
1705 if (srstDeasserted || powerRestored)
1707 /* Other than logging the event we can't do anything here.
1708 * Issuing a reset is a particularly bad idea as we might
1709 * be inside a reset already.
1713 return ERROR_OK;
1716 static void target_call_event_callbacks_all(enum target_event e) {
1717 target_t *target;
1718 target = all_targets;
1719 while (target) {
1720 target_call_event_callbacks(target, e);
1721 target = target->next;
1725 /* process target state changes */
1726 int handle_target(void *priv)
1728 int retval = ERROR_OK;
1730 /* we do not want to recurse here... */
1731 static int recursive = 0;
1732 if (! recursive)
1734 recursive = 1;
1735 sense_handler();
1736 /* danger! running these procedures can trigger srst assertions and power dropouts.
1737 * We need to avoid an infinite loop/recursion here and we do that by
1738 * clearing the flags after running these events.
1740 int did_something = 0;
1741 if (runSrstAsserted)
1743 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1744 Jim_Eval(interp, "srst_asserted");
1745 did_something = 1;
1747 if (runSrstDeasserted)
1749 Jim_Eval(interp, "srst_deasserted");
1750 did_something = 1;
1752 if (runPowerDropout)
1754 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1755 Jim_Eval(interp, "power_dropout");
1756 did_something = 1;
1758 if (runPowerRestore)
1760 Jim_Eval(interp, "power_restore");
1761 did_something = 1;
1764 if (did_something)
1766 /* clear detect flags */
1767 sense_handler();
1770 /* clear action flags */
1772 runSrstAsserted = 0;
1773 runSrstDeasserted = 0;
1774 runPowerRestore = 0;
1775 runPowerDropout = 0;
1777 recursive = 0;
1780 /* Poll targets for state changes unless that's globally disabled.
1781 * Skip targets that are currently disabled.
1783 for (target_t *target = all_targets;
1784 is_jtag_poll_safe() && target;
1785 target = target->next)
1787 if (!target->tap->enabled)
1788 continue;
1790 /* only poll target if we've got power and srst isn't asserted */
1791 if (!powerDropout && !srstAsserted)
1793 /* polling may fail silently until the target has been examined */
1794 if ((retval = target_poll(target)) != ERROR_OK)
1796 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1797 return retval;
1802 return retval;
1805 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1807 target_t *target;
1808 reg_t *reg = NULL;
1809 int count = 0;
1810 char *value;
1812 LOG_DEBUG("-");
1814 target = get_current_target(cmd_ctx);
1816 /* list all available registers for the current target */
1817 if (argc == 0)
1819 reg_cache_t *cache = target->reg_cache;
1821 count = 0;
1822 while (cache)
1824 int i;
1826 for (i = 0, reg = cache->reg_list;
1827 i < cache->num_regs;
1828 i++, reg++, count++)
1830 /* only print cached values if they are valid */
1831 if (reg->valid) {
1832 value = buf_to_str(reg->value,
1833 reg->size, 16);
1834 command_print(cmd_ctx,
1835 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1836 count, reg->name,
1837 reg->size, value,
1838 reg->dirty
1839 ? " (dirty)"
1840 : "");
1841 free(value);
1842 } else {
1843 command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1844 count, reg->name,
1845 reg->size) ;
1848 cache = cache->next;
1851 return ERROR_OK;
1854 /* access a single register by its ordinal number */
1855 if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1857 unsigned num;
1858 int retval = parse_uint(args[0], &num);
1859 if (ERROR_OK != retval)
1860 return ERROR_COMMAND_SYNTAX_ERROR;
1862 reg_cache_t *cache = target->reg_cache;
1863 count = 0;
1864 while (cache)
1866 int i;
1867 for (i = 0; i < cache->num_regs; i++)
1869 if (count++ == (int)num)
1871 reg = &cache->reg_list[i];
1872 break;
1875 if (reg)
1876 break;
1877 cache = cache->next;
1880 if (!reg)
1882 command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1883 return ERROR_OK;
1885 } else /* access a single register by its name */
1887 reg = register_get_by_name(target->reg_cache, args[0], 1);
1889 if (!reg)
1891 command_print(cmd_ctx, "register %s not found in current target", args[0]);
1892 return ERROR_OK;
1896 /* display a register */
1897 if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1899 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1900 reg->valid = 0;
1902 if (reg->valid == 0)
1904 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1905 arch_type->get(reg);
1907 value = buf_to_str(reg->value, reg->size, 16);
1908 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1909 free(value);
1910 return ERROR_OK;
1913 /* set register value */
1914 if (argc == 2)
1916 uint8_t *buf = malloc(CEIL(reg->size, 8));
1917 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1919 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1920 arch_type->set(reg, buf);
1922 value = buf_to_str(reg->value, reg->size, 16);
1923 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1924 free(value);
1926 free(buf);
1928 return ERROR_OK;
1931 command_print(cmd_ctx, "usage: reg <#|name> [value]");
1933 return ERROR_OK;
1936 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1938 int retval = ERROR_OK;
1939 target_t *target = get_current_target(cmd_ctx);
1941 if (argc == 0)
1943 command_print(cmd_ctx, "background polling: %s",
1944 jtag_poll_get_enabled() ? "on" : "off");
1945 command_print(cmd_ctx, "TAP: %s (%s)",
1946 target->tap->dotted_name,
1947 target->tap->enabled ? "enabled" : "disabled");
1948 if (!target->tap->enabled)
1949 return ERROR_OK;
1950 if ((retval = target_poll(target)) != ERROR_OK)
1951 return retval;
1952 if ((retval = target_arch_state(target)) != ERROR_OK)
1953 return retval;
1956 else if (argc == 1)
1958 if (strcmp(args[0], "on") == 0)
1960 jtag_poll_set_enabled(true);
1962 else if (strcmp(args[0], "off") == 0)
1964 jtag_poll_set_enabled(false);
1966 else
1968 command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1970 } else
1972 return ERROR_COMMAND_SYNTAX_ERROR;
1975 return retval;
1978 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1980 if (argc > 1)
1981 return ERROR_COMMAND_SYNTAX_ERROR;
1983 unsigned ms = 5000;
1984 if (1 == argc)
1986 int retval = parse_uint(args[0], &ms);
1987 if (ERROR_OK != retval)
1989 command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1990 return ERROR_COMMAND_SYNTAX_ERROR;
1992 // convert seconds (given) to milliseconds (needed)
1993 ms *= 1000;
1996 target_t *target = get_current_target(cmd_ctx);
1997 return target_wait_state(target, TARGET_HALTED, ms);
2000 /* wait for target state to change. The trick here is to have a low
2001 * latency for short waits and not to suck up all the CPU time
2002 * on longer waits.
2004 * After 500ms, keep_alive() is invoked
2006 int target_wait_state(target_t *target, enum target_state state, int ms)
2008 int retval;
2009 long long then = 0, cur;
2010 int once = 1;
2012 for (;;)
2014 if ((retval = target_poll(target)) != ERROR_OK)
2015 return retval;
2016 if (target->state == state)
2018 break;
2020 cur = timeval_ms();
2021 if (once)
2023 once = 0;
2024 then = timeval_ms();
2025 LOG_DEBUG("waiting for target %s...",
2026 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2029 if (cur-then > 500)
2031 keep_alive();
2034 if ((cur-then) > ms)
2036 LOG_ERROR("timed out while waiting for target %s",
2037 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2038 return ERROR_FAIL;
2042 return ERROR_OK;
2045 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2047 LOG_DEBUG("-");
2049 target_t *target = get_current_target(cmd_ctx);
2050 int retval = target_halt(target);
2051 if (ERROR_OK != retval)
2052 return retval;
2054 if (argc == 1)
2056 unsigned wait;
2057 retval = parse_uint(args[0], &wait);
2058 if (ERROR_OK != retval)
2059 return ERROR_COMMAND_SYNTAX_ERROR;
2060 if (!wait)
2061 return ERROR_OK;
2064 return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
2067 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2069 target_t *target = get_current_target(cmd_ctx);
2071 LOG_USER("requesting target halt and executing a soft reset");
2073 target->type->soft_reset_halt(target);
2075 return ERROR_OK;
2078 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2080 if (argc > 1)
2081 return ERROR_COMMAND_SYNTAX_ERROR;
2083 enum target_reset_mode reset_mode = RESET_RUN;
2084 if (argc == 1)
2086 const Jim_Nvp *n;
2087 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2088 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2089 return ERROR_COMMAND_SYNTAX_ERROR;
2091 reset_mode = n->value;
2094 /* reset *all* targets */
2095 return target_process_reset(cmd_ctx, reset_mode);
2099 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2101 int current = 1;
2102 if (argc > 1)
2103 return ERROR_COMMAND_SYNTAX_ERROR;
2105 target_t *target = get_current_target(cmd_ctx);
2106 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2108 /* with no args, resume from current pc, addr = 0,
2109 * with one arguments, addr = args[0],
2110 * handle breakpoints, not debugging */
2111 uint32_t addr = 0;
2112 if (argc == 1)
2114 int retval = parse_u32(args[0], &addr);
2115 if (ERROR_OK != retval)
2116 return retval;
2117 current = 0;
2120 return target_resume(target, current, addr, 1, 0);
2123 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2125 if (argc > 1)
2126 return ERROR_COMMAND_SYNTAX_ERROR;
2128 LOG_DEBUG("-");
2130 /* with no args, step from current pc, addr = 0,
2131 * with one argument addr = args[0],
2132 * handle breakpoints, debugging */
2133 uint32_t addr = 0;
2134 int current_pc = 1;
2135 if (argc == 1)
2137 int retval = parse_u32(args[0], &addr);
2138 if (ERROR_OK != retval)
2139 return retval;
2140 current_pc = 0;
2143 target_t *target = get_current_target(cmd_ctx);
2145 return target->type->step(target, current_pc, addr, 1);
2148 static void handle_md_output(struct command_context_s *cmd_ctx,
2149 struct target_s *target, uint32_t address, unsigned size,
2150 unsigned count, const uint8_t *buffer)
2152 const unsigned line_bytecnt = 32;
2153 unsigned line_modulo = line_bytecnt / size;
2155 char output[line_bytecnt * 4 + 1];
2156 unsigned output_len = 0;
2158 const char *value_fmt;
2159 switch (size) {
2160 case 4: value_fmt = "%8.8x "; break;
2161 case 2: value_fmt = "%4.2x "; break;
2162 case 1: value_fmt = "%2.2x "; break;
2163 default:
2164 LOG_ERROR("invalid memory read size: %u", size);
2165 exit(-1);
2168 for (unsigned i = 0; i < count; i++)
2170 if (i % line_modulo == 0)
2172 output_len += snprintf(output + output_len,
2173 sizeof(output) - output_len,
2174 "0x%8.8x: ",
2175 (unsigned)(address + (i*size)));
2178 uint32_t value = 0;
2179 const uint8_t *value_ptr = buffer + i * size;
2180 switch (size) {
2181 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2182 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2183 case 1: value = *value_ptr;
2185 output_len += snprintf(output + output_len,
2186 sizeof(output) - output_len,
2187 value_fmt, value);
2189 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2191 command_print(cmd_ctx, "%s", output);
2192 output_len = 0;
2197 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2199 if (argc < 1)
2200 return ERROR_COMMAND_SYNTAX_ERROR;
2202 unsigned size = 0;
2203 switch (cmd[2]) {
2204 case 'w': size = 4; break;
2205 case 'h': size = 2; break;
2206 case 'b': size = 1; break;
2207 default: return ERROR_COMMAND_SYNTAX_ERROR;
2210 bool physical=strcmp(args[0], "phys")==0;
2211 int (*fn)(struct target_s *target,
2212 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2213 if (physical)
2215 argc--;
2216 args++;
2217 fn=target_read_phys_memory;
2218 } else
2220 fn=target_read_memory;
2222 if ((argc < 1) || (argc > 2))
2224 return ERROR_COMMAND_SYNTAX_ERROR;
2226 uint32_t address;
2227 int retval = parse_u32(args[0], &address);
2228 if (ERROR_OK != retval)
2229 return retval;
2231 unsigned count = 1;
2232 if (argc == 2)
2234 retval = parse_uint(args[1], &count);
2235 if (ERROR_OK != retval)
2236 return retval;
2239 uint8_t *buffer = calloc(count, size);
2241 target_t *target = get_current_target(cmd_ctx);
2242 retval = fn(target, address, size, count, buffer);
2243 if (ERROR_OK == retval)
2244 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2246 free(buffer);
2248 return retval;
2251 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2253 if (argc < 2)
2255 return ERROR_COMMAND_SYNTAX_ERROR;
2257 bool physical=strcmp(args[0], "phys")==0;
2258 int (*fn)(struct target_s *target,
2259 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2260 if (physical)
2262 argc--;
2263 args++;
2264 fn=target_write_phys_memory;
2265 } else
2267 fn=target_write_memory;
2269 if ((argc < 2) || (argc > 3))
2270 return ERROR_COMMAND_SYNTAX_ERROR;
2272 uint32_t address;
2273 int retval = parse_u32(args[0], &address);
2274 if (ERROR_OK != retval)
2275 return retval;
2277 uint32_t value;
2278 retval = parse_u32(args[1], &value);
2279 if (ERROR_OK != retval)
2280 return retval;
2282 unsigned count = 1;
2283 if (argc == 3)
2285 retval = parse_uint(args[2], &count);
2286 if (ERROR_OK != retval)
2287 return retval;
2290 target_t *target = get_current_target(cmd_ctx);
2291 unsigned wordsize;
2292 uint8_t value_buf[4];
2293 switch (cmd[2])
2295 case 'w':
2296 wordsize = 4;
2297 target_buffer_set_u32(target, value_buf, value);
2298 break;
2299 case 'h':
2300 wordsize = 2;
2301 target_buffer_set_u16(target, value_buf, value);
2302 break;
2303 case 'b':
2304 wordsize = 1;
2305 value_buf[0] = value;
2306 break;
2307 default:
2308 return ERROR_COMMAND_SYNTAX_ERROR;
2310 for (unsigned i = 0; i < count; i++)
2312 retval = fn(target,
2313 address + i * wordsize, wordsize, 1, value_buf);
2314 if (ERROR_OK != retval)
2315 return retval;
2316 keep_alive();
2319 return ERROR_OK;
2323 static int parse_load_image_command_args(char **args, int argc,
2324 image_t *image, uint32_t *min_address, uint32_t *max_address)
2326 if (argc < 1 || argc > 5)
2327 return ERROR_COMMAND_SYNTAX_ERROR;
2329 /* a base address isn't always necessary,
2330 * default to 0x0 (i.e. don't relocate) */
2331 if (argc >= 2)
2333 uint32_t addr;
2334 int retval = parse_u32(args[1], &addr);
2335 if (ERROR_OK != retval)
2336 return ERROR_COMMAND_SYNTAX_ERROR;
2337 image->base_address = addr;
2338 image->base_address_set = 1;
2340 else
2341 image->base_address_set = 0;
2343 image->start_address_set = 0;
2345 if (argc >= 4)
2347 int retval = parse_u32(args[3], min_address);
2348 if (ERROR_OK != retval)
2349 return ERROR_COMMAND_SYNTAX_ERROR;
2351 if (argc == 5)
2353 int retval = parse_u32(args[4], max_address);
2354 if (ERROR_OK != retval)
2355 return ERROR_COMMAND_SYNTAX_ERROR;
2356 // use size (given) to find max (required)
2357 *max_address += *min_address;
2360 if (*min_address > *max_address)
2361 return ERROR_COMMAND_SYNTAX_ERROR;
2363 return ERROR_OK;
2366 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2368 uint8_t *buffer;
2369 uint32_t buf_cnt;
2370 uint32_t image_size;
2371 uint32_t min_address = 0;
2372 uint32_t max_address = 0xffffffff;
2373 int i;
2374 int retvaltemp;
2376 image_t image;
2378 duration_t duration;
2379 char *duration_text;
2381 int retval = parse_load_image_command_args(args, argc,
2382 &image, &min_address, &max_address);
2383 if (ERROR_OK != retval)
2384 return retval;
2386 target_t *target = get_current_target(cmd_ctx);
2387 duration_start_measure(&duration);
2389 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2391 return ERROR_OK;
2394 image_size = 0x0;
2395 retval = ERROR_OK;
2396 for (i = 0; i < image.num_sections; i++)
2398 buffer = malloc(image.sections[i].size);
2399 if (buffer == NULL)
2401 command_print(cmd_ctx,
2402 "error allocating buffer for section (%d bytes)",
2403 (int)(image.sections[i].size));
2404 break;
2407 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2409 free(buffer);
2410 break;
2413 uint32_t offset = 0;
2414 uint32_t length = buf_cnt;
2416 /* DANGER!!! beware of unsigned comparision here!!! */
2418 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2419 (image.sections[i].base_address < max_address))
2421 if (image.sections[i].base_address < min_address)
2423 /* clip addresses below */
2424 offset += min_address-image.sections[i].base_address;
2425 length -= offset;
2428 if (image.sections[i].base_address + buf_cnt > max_address)
2430 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2433 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2435 free(buffer);
2436 break;
2438 image_size += length;
2439 command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2440 (unsigned int)length,
2441 image.sections[i].base_address + offset);
2444 free(buffer);
2447 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2449 image_close(&image);
2450 return retvaltemp;
2453 if (retval == ERROR_OK)
2455 command_print(cmd_ctx, "downloaded %u byte in %s",
2456 (unsigned int)image_size,
2457 duration_text);
2459 free(duration_text);
2461 image_close(&image);
2463 return retval;
2467 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2469 fileio_t fileio;
2471 uint8_t buffer[560];
2472 int retvaltemp;
2474 duration_t duration;
2475 char *duration_text;
2477 target_t *target = get_current_target(cmd_ctx);
2479 if (argc != 3)
2481 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2482 return ERROR_OK;
2485 uint32_t address;
2486 int retval = parse_u32(args[1], &address);
2487 if (ERROR_OK != retval)
2488 return retval;
2490 uint32_t size;
2491 retval = parse_u32(args[2], &size);
2492 if (ERROR_OK != retval)
2493 return retval;
2495 if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2497 return ERROR_OK;
2500 duration_start_measure(&duration);
2502 while (size > 0)
2504 uint32_t size_written;
2505 uint32_t this_run_size = (size > 560) ? 560 : size;
2507 retval = target_read_buffer(target, address, this_run_size, buffer);
2508 if (retval != ERROR_OK)
2510 break;
2513 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2514 if (retval != ERROR_OK)
2516 break;
2519 size -= this_run_size;
2520 address += this_run_size;
2523 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2524 return retvaltemp;
2526 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2527 return retvaltemp;
2529 if (retval == ERROR_OK)
2531 command_print(cmd_ctx, "dumped %lld byte in %s",
2532 fileio.size, duration_text);
2533 free(duration_text);
2536 return retval;
2539 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2541 uint8_t *buffer;
2542 uint32_t buf_cnt;
2543 uint32_t image_size;
2544 int i;
2545 int retval, retvaltemp;
2546 uint32_t checksum = 0;
2547 uint32_t mem_checksum = 0;
2549 image_t image;
2551 duration_t duration;
2552 char *duration_text;
2554 target_t *target = get_current_target(cmd_ctx);
2556 if (argc < 1)
2558 return ERROR_COMMAND_SYNTAX_ERROR;
2561 if (!target)
2563 LOG_ERROR("no target selected");
2564 return ERROR_FAIL;
2567 duration_start_measure(&duration);
2569 if (argc >= 2)
2571 uint32_t addr;
2572 retval = parse_u32(args[1], &addr);
2573 if (ERROR_OK != retval)
2574 return ERROR_COMMAND_SYNTAX_ERROR;
2575 image.base_address = addr;
2576 image.base_address_set = 1;
2578 else
2580 image.base_address_set = 0;
2581 image.base_address = 0x0;
2584 image.start_address_set = 0;
2586 if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2588 return retval;
2591 image_size = 0x0;
2592 retval = ERROR_OK;
2593 for (i = 0; i < image.num_sections; i++)
2595 buffer = malloc(image.sections[i].size);
2596 if (buffer == NULL)
2598 command_print(cmd_ctx,
2599 "error allocating buffer for section (%d bytes)",
2600 (int)(image.sections[i].size));
2601 break;
2603 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2605 free(buffer);
2606 break;
2609 if (verify)
2611 /* calculate checksum of image */
2612 image_calculate_checksum(buffer, buf_cnt, &checksum);
2614 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2615 if (retval != ERROR_OK)
2617 free(buffer);
2618 break;
2621 if (checksum != mem_checksum)
2623 /* failed crc checksum, fall back to a binary compare */
2624 uint8_t *data;
2626 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2628 data = (uint8_t*)malloc(buf_cnt);
2630 /* Can we use 32bit word accesses? */
2631 int size = 1;
2632 int count = buf_cnt;
2633 if ((count % 4) == 0)
2635 size *= 4;
2636 count /= 4;
2638 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2639 if (retval == ERROR_OK)
2641 uint32_t t;
2642 for (t = 0; t < buf_cnt; t++)
2644 if (data[t] != buffer[t])
2646 command_print(cmd_ctx,
2647 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2648 (unsigned)(t + image.sections[i].base_address),
2649 data[t],
2650 buffer[t]);
2651 free(data);
2652 free(buffer);
2653 retval = ERROR_FAIL;
2654 goto done;
2656 if ((t%16384) == 0)
2658 keep_alive();
2663 free(data);
2665 } else
2667 command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2668 image.sections[i].base_address,
2669 buf_cnt);
2672 free(buffer);
2673 image_size += buf_cnt;
2675 done:
2677 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2679 image_close(&image);
2680 return retvaltemp;
2683 if (retval == ERROR_OK)
2685 command_print(cmd_ctx, "verified %u bytes in %s",
2686 (unsigned int)image_size,
2687 duration_text);
2689 free(duration_text);
2691 image_close(&image);
2693 return retval;
2696 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2698 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2701 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2703 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2706 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2708 target_t *target = get_current_target(cmd_ctx);
2709 breakpoint_t *breakpoint = target->breakpoints;
2710 while (breakpoint)
2712 if (breakpoint->type == BKPT_SOFT)
2714 char* buf = buf_to_str(breakpoint->orig_instr,
2715 breakpoint->length, 16);
2716 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2717 breakpoint->address,
2718 breakpoint->length,
2719 breakpoint->set, buf);
2720 free(buf);
2722 else
2724 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2725 breakpoint->address,
2726 breakpoint->length, breakpoint->set);
2729 breakpoint = breakpoint->next;
2731 return ERROR_OK;
2734 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2735 uint32_t addr, uint32_t length, int hw)
2737 target_t *target = get_current_target(cmd_ctx);
2738 int retval = breakpoint_add(target, addr, length, hw);
2739 if (ERROR_OK == retval)
2740 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2741 else
2742 LOG_ERROR("Failure setting breakpoint");
2743 return retval;
2746 static int handle_bp_command(struct command_context_s *cmd_ctx,
2747 char *cmd, char **args, int argc)
2749 if (argc == 0)
2750 return handle_bp_command_list(cmd_ctx);
2752 if (argc < 2 || argc > 3)
2754 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2755 return ERROR_COMMAND_SYNTAX_ERROR;
2758 uint32_t addr;
2759 int retval = parse_u32(args[0], &addr);
2760 if (ERROR_OK != retval)
2761 return retval;
2763 uint32_t length;
2764 retval = parse_u32(args[1], &length);
2765 if (ERROR_OK != retval)
2766 return retval;
2768 int hw = BKPT_SOFT;
2769 if (argc == 3)
2771 if (strcmp(args[2], "hw") == 0)
2772 hw = BKPT_HARD;
2773 else
2774 return ERROR_COMMAND_SYNTAX_ERROR;
2777 return handle_bp_command_set(cmd_ctx, addr, length, hw);
2780 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2782 if (argc != 1)
2783 return ERROR_COMMAND_SYNTAX_ERROR;
2785 uint32_t addr;
2786 int retval = parse_u32(args[0], &addr);
2787 if (ERROR_OK != retval)
2788 return retval;
2790 target_t *target = get_current_target(cmd_ctx);
2791 breakpoint_remove(target, addr);
2793 return ERROR_OK;
2796 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2798 target_t *target = get_current_target(cmd_ctx);
2800 if (argc == 0)
2802 watchpoint_t *watchpoint = target->watchpoints;
2804 while (watchpoint)
2806 command_print(cmd_ctx,
2807 "address: 0x%8.8" PRIx32 ", len: 0x%8.8x, r/w/a: %i, value: 0x%8.8" PRIx32 ", mask: 0x%8.8" PRIx32 "",
2808 watchpoint->address,
2809 watchpoint->length,
2810 (int)(watchpoint->rw),
2811 watchpoint->value,
2812 watchpoint->mask);
2813 watchpoint = watchpoint->next;
2815 return ERROR_OK;
2818 enum watchpoint_rw type = WPT_ACCESS;
2819 uint32_t addr = 0;
2820 uint32_t length = 0;
2821 uint32_t data_value = 0x0;
2822 uint32_t data_mask = 0xffffffff;
2823 int retval;
2825 switch (argc)
2827 case 5:
2828 retval = parse_u32(args[4], &data_mask);
2829 if (ERROR_OK != retval)
2830 return retval;
2831 // fall through
2832 case 4:
2833 retval = parse_u32(args[3], &data_value);
2834 if (ERROR_OK != retval)
2835 return retval;
2836 // fall through
2837 case 3:
2838 switch (args[2][0])
2840 case 'r':
2841 type = WPT_READ;
2842 break;
2843 case 'w':
2844 type = WPT_WRITE;
2845 break;
2846 case 'a':
2847 type = WPT_ACCESS;
2848 break;
2849 default:
2850 LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2851 return ERROR_COMMAND_SYNTAX_ERROR;
2853 // fall through
2854 case 2:
2855 retval = parse_u32(args[1], &length);
2856 if (ERROR_OK != retval)
2857 return retval;
2858 retval = parse_u32(args[0], &addr);
2859 if (ERROR_OK != retval)
2860 return retval;
2861 break;
2863 default:
2864 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2865 return ERROR_COMMAND_SYNTAX_ERROR;
2868 retval = watchpoint_add(target, addr, length, type,
2869 data_value, data_mask);
2870 if (ERROR_OK != retval)
2871 LOG_ERROR("Failure setting watchpoints");
2873 return retval;
2876 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2878 if (argc != 1)
2879 return ERROR_COMMAND_SYNTAX_ERROR;
2881 uint32_t addr;
2882 int retval = parse_u32(args[0], &addr);
2883 if (ERROR_OK != retval)
2884 return retval;
2886 target_t *target = get_current_target(cmd_ctx);
2887 watchpoint_remove(target, addr);
2889 return ERROR_OK;
2894 * Translate a virtual address to a physical address.
2896 * The low-level target implementation must have logged a detailed error
2897 * which is forwarded to telnet/GDB session.
2899 static int handle_virt2phys_command(command_context_t *cmd_ctx,
2900 char *cmd, char **args, int argc)
2902 if (argc != 1)
2903 return ERROR_COMMAND_SYNTAX_ERROR;
2905 uint32_t va;
2906 int retval = parse_u32(args[0], &va);
2907 if (ERROR_OK != retval)
2908 return retval;
2909 uint32_t pa;
2911 target_t *target = get_current_target(cmd_ctx);
2912 retval = target->type->virt2phys(target, va, &pa);
2913 if (retval == ERROR_OK)
2914 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2916 return retval;
2919 static void writeData(FILE *f, const void *data, size_t len)
2921 size_t written = fwrite(data, 1, len, f);
2922 if (written != len)
2923 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2926 static void writeLong(FILE *f, int l)
2928 int i;
2929 for (i = 0; i < 4; i++)
2931 char c = (l >> (i*8))&0xff;
2932 writeData(f, &c, 1);
2937 static void writeString(FILE *f, char *s)
2939 writeData(f, s, strlen(s));
2942 /* Dump a gmon.out histogram file. */
2943 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
2945 uint32_t i;
2946 FILE *f = fopen(filename, "w");
2947 if (f == NULL)
2948 return;
2949 writeString(f, "gmon");
2950 writeLong(f, 0x00000001); /* Version */
2951 writeLong(f, 0); /* padding */
2952 writeLong(f, 0); /* padding */
2953 writeLong(f, 0); /* padding */
2955 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2956 writeData(f, &zero, 1);
2958 /* figure out bucket size */
2959 uint32_t min = samples[0];
2960 uint32_t max = samples[0];
2961 for (i = 0; i < sampleNum; i++)
2963 if (min > samples[i])
2965 min = samples[i];
2967 if (max < samples[i])
2969 max = samples[i];
2973 int addressSpace = (max-min + 1);
2975 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2976 uint32_t length = addressSpace;
2977 if (length > maxBuckets)
2979 length = maxBuckets;
2981 int *buckets = malloc(sizeof(int)*length);
2982 if (buckets == NULL)
2984 fclose(f);
2985 return;
2987 memset(buckets, 0, sizeof(int)*length);
2988 for (i = 0; i < sampleNum;i++)
2990 uint32_t address = samples[i];
2991 long long a = address-min;
2992 long long b = length-1;
2993 long long c = addressSpace-1;
2994 int index = (a*b)/c; /* danger!!!! int32 overflows */
2995 buckets[index]++;
2998 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2999 writeLong(f, min); /* low_pc */
3000 writeLong(f, max); /* high_pc */
3001 writeLong(f, length); /* # of samples */
3002 writeLong(f, 64000000); /* 64MHz */
3003 writeString(f, "seconds");
3004 for (i = 0; i < (15-strlen("seconds")); i++)
3005 writeData(f, &zero, 1);
3006 writeString(f, "s");
3008 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3010 char *data = malloc(2*length);
3011 if (data != NULL)
3013 for (i = 0; i < length;i++)
3015 int val;
3016 val = buckets[i];
3017 if (val > 65535)
3019 val = 65535;
3021 data[i*2]=val&0xff;
3022 data[i*2 + 1]=(val >> 8)&0xff;
3024 free(buckets);
3025 writeData(f, data, length * 2);
3026 free(data);
3027 } else
3029 free(buckets);
3032 fclose(f);
3035 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
3036 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
3038 target_t *target = get_current_target(cmd_ctx);
3039 struct timeval timeout, now;
3041 gettimeofday(&timeout, NULL);
3042 if (argc != 2)
3044 return ERROR_COMMAND_SYNTAX_ERROR;
3046 unsigned offset;
3047 int retval = parse_uint(args[0], &offset);
3048 if (ERROR_OK != retval)
3049 return retval;
3051 timeval_add_time(&timeout, offset, 0);
3053 command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3055 static const int maxSample = 10000;
3056 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3057 if (samples == NULL)
3058 return ERROR_OK;
3060 int numSamples = 0;
3061 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3062 reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
3064 for (;;)
3066 target_poll(target);
3067 if (target->state == TARGET_HALTED)
3069 uint32_t t=*((uint32_t *)reg->value);
3070 samples[numSamples++]=t;
3071 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3072 target_poll(target);
3073 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3074 } else if (target->state == TARGET_RUNNING)
3076 /* We want to quickly sample the PC. */
3077 if ((retval = target_halt(target)) != ERROR_OK)
3079 free(samples);
3080 return retval;
3082 } else
3084 command_print(cmd_ctx, "Target not halted or running");
3085 retval = ERROR_OK;
3086 break;
3088 if (retval != ERROR_OK)
3090 break;
3093 gettimeofday(&now, NULL);
3094 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3096 command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3097 if ((retval = target_poll(target)) != ERROR_OK)
3099 free(samples);
3100 return retval;
3102 if (target->state == TARGET_HALTED)
3104 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3106 if ((retval = target_poll(target)) != ERROR_OK)
3108 free(samples);
3109 return retval;
3111 writeGmon(samples, numSamples, args[1]);
3112 command_print(cmd_ctx, "Wrote %s", args[1]);
3113 break;
3116 free(samples);
3118 return ERROR_OK;
3121 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3123 char *namebuf;
3124 Jim_Obj *nameObjPtr, *valObjPtr;
3125 int result;
3127 namebuf = alloc_printf("%s(%d)", varname, idx);
3128 if (!namebuf)
3129 return JIM_ERR;
3131 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3132 valObjPtr = Jim_NewIntObj(interp, val);
3133 if (!nameObjPtr || !valObjPtr)
3135 free(namebuf);
3136 return JIM_ERR;
3139 Jim_IncrRefCount(nameObjPtr);
3140 Jim_IncrRefCount(valObjPtr);
3141 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3142 Jim_DecrRefCount(interp, nameObjPtr);
3143 Jim_DecrRefCount(interp, valObjPtr);
3144 free(namebuf);
3145 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3146 return result;
3149 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3151 command_context_t *context;
3152 target_t *target;
3154 context = Jim_GetAssocData(interp, "context");
3155 if (context == NULL)
3157 LOG_ERROR("mem2array: no command context");
3158 return JIM_ERR;
3160 target = get_current_target(context);
3161 if (target == NULL)
3163 LOG_ERROR("mem2array: no current target");
3164 return JIM_ERR;
3167 return target_mem2array(interp, target, argc-1, argv + 1);
3170 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3172 long l;
3173 uint32_t width;
3174 int len;
3175 uint32_t addr;
3176 uint32_t count;
3177 uint32_t v;
3178 const char *varname;
3179 uint8_t buffer[4096];
3180 int n, e, retval;
3181 uint32_t i;
3183 /* argv[1] = name of array to receive the data
3184 * argv[2] = desired width
3185 * argv[3] = memory address
3186 * argv[4] = count of times to read
3188 if (argc != 4) {
3189 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3190 return JIM_ERR;
3192 varname = Jim_GetString(argv[0], &len);
3193 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3195 e = Jim_GetLong(interp, argv[1], &l);
3196 width = l;
3197 if (e != JIM_OK) {
3198 return e;
3201 e = Jim_GetLong(interp, argv[2], &l);
3202 addr = l;
3203 if (e != JIM_OK) {
3204 return e;
3206 e = Jim_GetLong(interp, argv[3], &l);
3207 len = l;
3208 if (e != JIM_OK) {
3209 return e;
3211 switch (width) {
3212 case 8:
3213 width = 1;
3214 break;
3215 case 16:
3216 width = 2;
3217 break;
3218 case 32:
3219 width = 4;
3220 break;
3221 default:
3222 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3223 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3224 return JIM_ERR;
3226 if (len == 0) {
3227 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3228 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3229 return JIM_ERR;
3231 if ((addr + (len * width)) < addr) {
3232 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3233 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3234 return JIM_ERR;
3236 /* absurd transfer size? */
3237 if (len > 65536) {
3238 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3239 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3240 return JIM_ERR;
3243 if ((width == 1) ||
3244 ((width == 2) && ((addr & 1) == 0)) ||
3245 ((width == 4) && ((addr & 3) == 0))) {
3246 /* all is well */
3247 } else {
3248 char buf[100];
3249 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3250 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3251 addr,
3252 width);
3253 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3254 return JIM_ERR;
3257 /* Transfer loop */
3259 /* index counter */
3260 n = 0;
3261 /* assume ok */
3262 e = JIM_OK;
3263 while (len) {
3264 /* Slurp... in buffer size chunks */
3266 count = len; /* in objects.. */
3267 if (count > (sizeof(buffer)/width)) {
3268 count = (sizeof(buffer)/width);
3271 retval = target_read_memory(target, addr, width, count, buffer);
3272 if (retval != ERROR_OK) {
3273 /* BOO !*/
3274 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3275 (unsigned int)addr,
3276 (int)width,
3277 (int)count);
3278 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3279 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3280 e = JIM_ERR;
3281 len = 0;
3282 } else {
3283 v = 0; /* shut up gcc */
3284 for (i = 0 ;i < count ;i++, n++) {
3285 switch (width) {
3286 case 4:
3287 v = target_buffer_get_u32(target, &buffer[i*width]);
3288 break;
3289 case 2:
3290 v = target_buffer_get_u16(target, &buffer[i*width]);
3291 break;
3292 case 1:
3293 v = buffer[i] & 0x0ff;
3294 break;
3296 new_int_array_element(interp, varname, n, v);
3298 len -= count;
3302 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3304 return JIM_OK;
3307 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3309 char *namebuf;
3310 Jim_Obj *nameObjPtr, *valObjPtr;
3311 int result;
3312 long l;
3314 namebuf = alloc_printf("%s(%d)", varname, idx);
3315 if (!namebuf)
3316 return JIM_ERR;
3318 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3319 if (!nameObjPtr)
3321 free(namebuf);
3322 return JIM_ERR;
3325 Jim_IncrRefCount(nameObjPtr);
3326 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3327 Jim_DecrRefCount(interp, nameObjPtr);
3328 free(namebuf);
3329 if (valObjPtr == NULL)
3330 return JIM_ERR;
3332 result = Jim_GetLong(interp, valObjPtr, &l);
3333 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3334 *val = l;
3335 return result;
3338 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3340 command_context_t *context;
3341 target_t *target;
3343 context = Jim_GetAssocData(interp, "context");
3344 if (context == NULL) {
3345 LOG_ERROR("array2mem: no command context");
3346 return JIM_ERR;
3348 target = get_current_target(context);
3349 if (target == NULL) {
3350 LOG_ERROR("array2mem: no current target");
3351 return JIM_ERR;
3354 return target_array2mem(interp,target, argc-1, argv + 1);
3357 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3359 long l;
3360 uint32_t width;
3361 int len;
3362 uint32_t addr;
3363 uint32_t count;
3364 uint32_t v;
3365 const char *varname;
3366 uint8_t buffer[4096];
3367 int n, e, retval;
3368 uint32_t i;
3370 /* argv[1] = name of array to get the data
3371 * argv[2] = desired width
3372 * argv[3] = memory address
3373 * argv[4] = count to write
3375 if (argc != 4) {
3376 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3377 return JIM_ERR;
3379 varname = Jim_GetString(argv[0], &len);
3380 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3382 e = Jim_GetLong(interp, argv[1], &l);
3383 width = l;
3384 if (e != JIM_OK) {
3385 return e;
3388 e = Jim_GetLong(interp, argv[2], &l);
3389 addr = l;
3390 if (e != JIM_OK) {
3391 return e;
3393 e = Jim_GetLong(interp, argv[3], &l);
3394 len = l;
3395 if (e != JIM_OK) {
3396 return e;
3398 switch (width) {
3399 case 8:
3400 width = 1;
3401 break;
3402 case 16:
3403 width = 2;
3404 break;
3405 case 32:
3406 width = 4;
3407 break;
3408 default:
3409 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3410 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3411 return JIM_ERR;
3413 if (len == 0) {
3414 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3415 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3416 return JIM_ERR;
3418 if ((addr + (len * width)) < addr) {
3419 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3420 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3421 return JIM_ERR;
3423 /* absurd transfer size? */
3424 if (len > 65536) {
3425 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3426 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3427 return JIM_ERR;
3430 if ((width == 1) ||
3431 ((width == 2) && ((addr & 1) == 0)) ||
3432 ((width == 4) && ((addr & 3) == 0))) {
3433 /* all is well */
3434 } else {
3435 char buf[100];
3436 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3437 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3438 (unsigned int)addr,
3439 (int)width);
3440 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3441 return JIM_ERR;
3444 /* Transfer loop */
3446 /* index counter */
3447 n = 0;
3448 /* assume ok */
3449 e = JIM_OK;
3450 while (len) {
3451 /* Slurp... in buffer size chunks */
3453 count = len; /* in objects.. */
3454 if (count > (sizeof(buffer)/width)) {
3455 count = (sizeof(buffer)/width);
3458 v = 0; /* shut up gcc */
3459 for (i = 0 ;i < count ;i++, n++) {
3460 get_int_array_element(interp, varname, n, &v);
3461 switch (width) {
3462 case 4:
3463 target_buffer_set_u32(target, &buffer[i*width], v);
3464 break;
3465 case 2:
3466 target_buffer_set_u16(target, &buffer[i*width], v);
3467 break;
3468 case 1:
3469 buffer[i] = v & 0x0ff;
3470 break;
3473 len -= count;
3475 retval = target_write_memory(target, addr, width, count, buffer);
3476 if (retval != ERROR_OK) {
3477 /* BOO !*/
3478 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3479 (unsigned int)addr,
3480 (int)width,
3481 (int)count);
3482 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3483 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3484 e = JIM_ERR;
3485 len = 0;
3489 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3491 return JIM_OK;
3494 void target_all_handle_event(enum target_event e)
3496 target_t *target;
3498 LOG_DEBUG("**all*targets: event: %d, %s",
3499 (int)e,
3500 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3502 target = all_targets;
3503 while (target) {
3504 target_handle_event(target, e);
3505 target = target->next;
3510 /* FIX? should we propagate errors here rather than printing them
3511 * and continuing?
3513 void target_handle_event(target_t *target, enum target_event e)
3515 target_event_action_t *teap;
3517 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3518 if (teap->event == e) {
3519 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3520 target->target_number,
3521 target->cmd_name,
3522 target_get_name(target),
3524 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3525 Jim_GetString(teap->body, NULL));
3526 if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3528 Jim_PrintErrorMessage(interp);
3534 enum target_cfg_param {
3535 TCFG_TYPE,
3536 TCFG_EVENT,
3537 TCFG_WORK_AREA_VIRT,
3538 TCFG_WORK_AREA_PHYS,
3539 TCFG_WORK_AREA_SIZE,
3540 TCFG_WORK_AREA_BACKUP,
3541 TCFG_ENDIAN,
3542 TCFG_VARIANT,
3543 TCFG_CHAIN_POSITION,
3546 static Jim_Nvp nvp_config_opts[] = {
3547 { .name = "-type", .value = TCFG_TYPE },
3548 { .name = "-event", .value = TCFG_EVENT },
3549 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3550 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3551 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3552 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3553 { .name = "-endian" , .value = TCFG_ENDIAN },
3554 { .name = "-variant", .value = TCFG_VARIANT },
3555 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3557 { .name = NULL, .value = -1 }
3560 static int target_configure(Jim_GetOptInfo *goi, target_t *target)
3562 Jim_Nvp *n;
3563 Jim_Obj *o;
3564 jim_wide w;
3565 char *cp;
3566 int e;
3568 /* parse config or cget options ... */
3569 while (goi->argc > 0) {
3570 Jim_SetEmptyResult(goi->interp);
3571 /* Jim_GetOpt_Debug(goi); */
3573 if (target->type->target_jim_configure) {
3574 /* target defines a configure function */
3575 /* target gets first dibs on parameters */
3576 e = (*(target->type->target_jim_configure))(target, goi);
3577 if (e == JIM_OK) {
3578 /* more? */
3579 continue;
3581 if (e == JIM_ERR) {
3582 /* An error */
3583 return e;
3585 /* otherwise we 'continue' below */
3587 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3588 if (e != JIM_OK) {
3589 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3590 return e;
3592 switch (n->value) {
3593 case TCFG_TYPE:
3594 /* not setable */
3595 if (goi->isconfigure) {
3596 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3597 return JIM_ERR;
3598 } else {
3599 no_params:
3600 if (goi->argc != 0) {
3601 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3602 return JIM_ERR;
3605 Jim_SetResultString(goi->interp, target_get_name(target), -1);
3606 /* loop for more */
3607 break;
3608 case TCFG_EVENT:
3609 if (goi->argc == 0) {
3610 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3611 return JIM_ERR;
3614 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3615 if (e != JIM_OK) {
3616 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3617 return e;
3620 if (goi->isconfigure) {
3621 if (goi->argc != 1) {
3622 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3623 return JIM_ERR;
3625 } else {
3626 if (goi->argc != 0) {
3627 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3628 return JIM_ERR;
3633 target_event_action_t *teap;
3635 teap = target->event_action;
3636 /* replace existing? */
3637 while (teap) {
3638 if (teap->event == (enum target_event)n->value) {
3639 break;
3641 teap = teap->next;
3644 if (goi->isconfigure) {
3645 bool replace = true;
3646 if (teap == NULL) {
3647 /* create new */
3648 teap = calloc(1, sizeof(*teap));
3649 replace = false;
3651 teap->event = n->value;
3652 Jim_GetOpt_Obj(goi, &o);
3653 if (teap->body) {
3654 Jim_DecrRefCount(interp, teap->body);
3656 teap->body = Jim_DuplicateObj(goi->interp, o);
3658 * FIXME:
3659 * Tcl/TK - "tk events" have a nice feature.
3660 * See the "BIND" command.
3661 * We should support that here.
3662 * You can specify %X and %Y in the event code.
3663 * The idea is: %T - target name.
3664 * The idea is: %N - target number
3665 * The idea is: %E - event name.
3667 Jim_IncrRefCount(teap->body);
3669 if (!replace)
3671 /* add to head of event list */
3672 teap->next = target->event_action;
3673 target->event_action = teap;
3675 Jim_SetEmptyResult(goi->interp);
3676 } else {
3677 /* get */
3678 if (teap == NULL) {
3679 Jim_SetEmptyResult(goi->interp);
3680 } else {
3681 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3685 /* loop for more */
3686 break;
3688 case TCFG_WORK_AREA_VIRT:
3689 if (goi->isconfigure) {
3690 target_free_all_working_areas(target);
3691 e = Jim_GetOpt_Wide(goi, &w);
3692 if (e != JIM_OK) {
3693 return e;
3695 target->working_area_virt = w;
3696 } else {
3697 if (goi->argc != 0) {
3698 goto no_params;
3701 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3702 /* loop for more */
3703 break;
3705 case TCFG_WORK_AREA_PHYS:
3706 if (goi->isconfigure) {
3707 target_free_all_working_areas(target);
3708 e = Jim_GetOpt_Wide(goi, &w);
3709 if (e != JIM_OK) {
3710 return e;
3712 target->working_area_phys = w;
3713 } else {
3714 if (goi->argc != 0) {
3715 goto no_params;
3718 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3719 /* loop for more */
3720 break;
3722 case TCFG_WORK_AREA_SIZE:
3723 if (goi->isconfigure) {
3724 target_free_all_working_areas(target);
3725 e = Jim_GetOpt_Wide(goi, &w);
3726 if (e != JIM_OK) {
3727 return e;
3729 target->working_area_size = w;
3730 } else {
3731 if (goi->argc != 0) {
3732 goto no_params;
3735 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3736 /* loop for more */
3737 break;
3739 case TCFG_WORK_AREA_BACKUP:
3740 if (goi->isconfigure) {
3741 target_free_all_working_areas(target);
3742 e = Jim_GetOpt_Wide(goi, &w);
3743 if (e != JIM_OK) {
3744 return e;
3746 /* make this exactly 1 or 0 */
3747 target->backup_working_area = (!!w);
3748 } else {
3749 if (goi->argc != 0) {
3750 goto no_params;
3753 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3754 /* loop for more e*/
3755 break;
3757 case TCFG_ENDIAN:
3758 if (goi->isconfigure) {
3759 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3760 if (e != JIM_OK) {
3761 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3762 return e;
3764 target->endianness = n->value;
3765 } else {
3766 if (goi->argc != 0) {
3767 goto no_params;
3770 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3771 if (n->name == NULL) {
3772 target->endianness = TARGET_LITTLE_ENDIAN;
3773 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3775 Jim_SetResultString(goi->interp, n->name, -1);
3776 /* loop for more */
3777 break;
3779 case TCFG_VARIANT:
3780 if (goi->isconfigure) {
3781 if (goi->argc < 1) {
3782 Jim_SetResult_sprintf(goi->interp,
3783 "%s ?STRING?",
3784 n->name);
3785 return JIM_ERR;
3787 if (target->variant) {
3788 free((void *)(target->variant));
3790 e = Jim_GetOpt_String(goi, &cp, NULL);
3791 target->variant = strdup(cp);
3792 } else {
3793 if (goi->argc != 0) {
3794 goto no_params;
3797 Jim_SetResultString(goi->interp, target->variant,-1);
3798 /* loop for more */
3799 break;
3800 case TCFG_CHAIN_POSITION:
3801 if (goi->isconfigure) {
3802 Jim_Obj *o;
3803 jtag_tap_t *tap;
3804 target_free_all_working_areas(target);
3805 e = Jim_GetOpt_Obj(goi, &o);
3806 if (e != JIM_OK) {
3807 return e;
3809 tap = jtag_tap_by_jim_obj(goi->interp, o);
3810 if (tap == NULL) {
3811 return JIM_ERR;
3813 /* make this exactly 1 or 0 */
3814 target->tap = tap;
3815 } else {
3816 if (goi->argc != 0) {
3817 goto no_params;
3820 Jim_SetResultString(interp, target->tap->dotted_name, -1);
3821 /* loop for more e*/
3822 break;
3824 } /* while (goi->argc) */
3827 /* done - we return */
3828 return JIM_OK;
3831 /** this is the 'tcl' handler for the target specific command */
3832 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3834 Jim_GetOptInfo goi;
3835 jim_wide a,b,c;
3836 int x,y,z;
3837 uint8_t target_buf[32];
3838 Jim_Nvp *n;
3839 target_t *target;
3840 struct command_context_s *cmd_ctx;
3841 int e;
3843 enum {
3844 TS_CMD_CONFIGURE,
3845 TS_CMD_CGET,
3847 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3848 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3849 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3850 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3851 TS_CMD_EXAMINE,
3852 TS_CMD_POLL,
3853 TS_CMD_RESET,
3854 TS_CMD_HALT,
3855 TS_CMD_WAITSTATE,
3856 TS_CMD_EVENTLIST,
3857 TS_CMD_CURSTATE,
3858 TS_CMD_INVOKE_EVENT,
3861 static const Jim_Nvp target_options[] = {
3862 { .name = "configure", .value = TS_CMD_CONFIGURE },
3863 { .name = "cget", .value = TS_CMD_CGET },
3864 { .name = "mww", .value = TS_CMD_MWW },
3865 { .name = "mwh", .value = TS_CMD_MWH },
3866 { .name = "mwb", .value = TS_CMD_MWB },
3867 { .name = "mdw", .value = TS_CMD_MDW },
3868 { .name = "mdh", .value = TS_CMD_MDH },
3869 { .name = "mdb", .value = TS_CMD_MDB },
3870 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3871 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3872 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3873 { .name = "curstate", .value = TS_CMD_CURSTATE },
3875 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3876 { .name = "arp_poll", .value = TS_CMD_POLL },
3877 { .name = "arp_reset", .value = TS_CMD_RESET },
3878 { .name = "arp_halt", .value = TS_CMD_HALT },
3879 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3880 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3882 { .name = NULL, .value = -1 },
3885 /* go past the "command" */
3886 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3888 target = Jim_CmdPrivData(goi.interp);
3889 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3891 /* commands here are in an NVP table */
3892 e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3893 if (e != JIM_OK) {
3894 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3895 return e;
3897 /* Assume blank result */
3898 Jim_SetEmptyResult(goi.interp);
3900 switch (n->value) {
3901 case TS_CMD_CONFIGURE:
3902 if (goi.argc < 2) {
3903 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3904 return JIM_ERR;
3906 goi.isconfigure = 1;
3907 return target_configure(&goi, target);
3908 case TS_CMD_CGET:
3909 // some things take params
3910 if (goi.argc < 1) {
3911 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3912 return JIM_ERR;
3914 goi.isconfigure = 0;
3915 return target_configure(&goi, target);
3916 break;
3917 case TS_CMD_MWW:
3918 case TS_CMD_MWH:
3919 case TS_CMD_MWB:
3920 /* argv[0] = cmd
3921 * argv[1] = address
3922 * argv[2] = data
3923 * argv[3] = optional count.
3926 if ((goi.argc == 2) || (goi.argc == 3)) {
3927 /* all is well */
3928 } else {
3929 mwx_error:
3930 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3931 return JIM_ERR;
3934 e = Jim_GetOpt_Wide(&goi, &a);
3935 if (e != JIM_OK) {
3936 goto mwx_error;
3939 e = Jim_GetOpt_Wide(&goi, &b);
3940 if (e != JIM_OK) {
3941 goto mwx_error;
3943 if (goi.argc == 3) {
3944 e = Jim_GetOpt_Wide(&goi, &c);
3945 if (e != JIM_OK) {
3946 goto mwx_error;
3948 } else {
3949 c = 1;
3952 switch (n->value) {
3953 case TS_CMD_MWW:
3954 target_buffer_set_u32(target, target_buf, b);
3955 b = 4;
3956 break;
3957 case TS_CMD_MWH:
3958 target_buffer_set_u16(target, target_buf, b);
3959 b = 2;
3960 break;
3961 case TS_CMD_MWB:
3962 target_buffer_set_u8(target, target_buf, b);
3963 b = 1;
3964 break;
3966 for (x = 0 ; x < c ; x++) {
3967 e = target_write_memory(target, a, b, 1, target_buf);
3968 if (e != ERROR_OK) {
3969 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3970 return JIM_ERR;
3972 /* b = width */
3973 a = a + b;
3975 return JIM_OK;
3976 break;
3978 /* display */
3979 case TS_CMD_MDW:
3980 case TS_CMD_MDH:
3981 case TS_CMD_MDB:
3982 /* argv[0] = command
3983 * argv[1] = address
3984 * argv[2] = optional count
3986 if ((goi.argc == 2) || (goi.argc == 3)) {
3987 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3988 return JIM_ERR;
3990 e = Jim_GetOpt_Wide(&goi, &a);
3991 if (e != JIM_OK) {
3992 return JIM_ERR;
3994 if (goi.argc) {
3995 e = Jim_GetOpt_Wide(&goi, &c);
3996 if (e != JIM_OK) {
3997 return JIM_ERR;
3999 } else {
4000 c = 1;
4002 b = 1; /* shut up gcc */
4003 switch (n->value) {
4004 case TS_CMD_MDW:
4005 b = 4;
4006 break;
4007 case TS_CMD_MDH:
4008 b = 2;
4009 break;
4010 case TS_CMD_MDB:
4011 b = 1;
4012 break;
4015 /* convert to "bytes" */
4016 c = c * b;
4017 /* count is now in 'BYTES' */
4018 while (c > 0) {
4019 y = c;
4020 if (y > 16) {
4021 y = 16;
4023 e = target_read_memory(target, a, b, y / b, target_buf);
4024 if (e != ERROR_OK) {
4025 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4026 return JIM_ERR;
4029 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4030 switch (b) {
4031 case 4:
4032 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
4033 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
4034 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4036 for (; (x < 16) ; x += 4) {
4037 Jim_fprintf(interp, interp->cookie_stdout, " ");
4039 break;
4040 case 2:
4041 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
4042 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
4043 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4045 for (; (x < 16) ; x += 2) {
4046 Jim_fprintf(interp, interp->cookie_stdout, " ");
4048 break;
4049 case 1:
4050 default:
4051 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4052 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4053 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4055 for (; (x < 16) ; x += 1) {
4056 Jim_fprintf(interp, interp->cookie_stdout, " ");
4058 break;
4060 /* ascii-ify the bytes */
4061 for (x = 0 ; x < y ; x++) {
4062 if ((target_buf[x] >= 0x20) &&
4063 (target_buf[x] <= 0x7e)) {
4064 /* good */
4065 } else {
4066 /* smack it */
4067 target_buf[x] = '.';
4070 /* space pad */
4071 while (x < 16) {
4072 target_buf[x] = ' ';
4073 x++;
4075 /* terminate */
4076 target_buf[16] = 0;
4077 /* print - with a newline */
4078 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4079 /* NEXT... */
4080 c -= 16;
4081 a += 16;
4083 return JIM_OK;
4084 case TS_CMD_MEM2ARRAY:
4085 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4086 break;
4087 case TS_CMD_ARRAY2MEM:
4088 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4089 break;
4090 case TS_CMD_EXAMINE:
4091 if (goi.argc) {
4092 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4093 return JIM_ERR;
4095 if (!target->tap->enabled)
4096 goto err_tap_disabled;
4097 e = target->type->examine(target);
4098 if (e != ERROR_OK) {
4099 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4100 return JIM_ERR;
4102 return JIM_OK;
4103 case TS_CMD_POLL:
4104 if (goi.argc) {
4105 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4106 return JIM_ERR;
4108 if (!target->tap->enabled)
4109 goto err_tap_disabled;
4110 if (!(target_was_examined(target))) {
4111 e = ERROR_TARGET_NOT_EXAMINED;
4112 } else {
4113 e = target->type->poll(target);
4115 if (e != ERROR_OK) {
4116 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4117 return JIM_ERR;
4118 } else {
4119 return JIM_OK;
4121 break;
4122 case TS_CMD_RESET:
4123 if (goi.argc != 2) {
4124 Jim_WrongNumArgs(interp, 2, argv,
4125 "([tT]|[fF]|assert|deassert) BOOL");
4126 return JIM_ERR;
4128 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4129 if (e != JIM_OK) {
4130 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4131 return e;
4133 /* the halt or not param */
4134 e = Jim_GetOpt_Wide(&goi, &a);
4135 if (e != JIM_OK) {
4136 return e;
4138 if (!target->tap->enabled)
4139 goto err_tap_disabled;
4140 if (!target->type->assert_reset
4141 || !target->type->deassert_reset) {
4142 Jim_SetResult_sprintf(interp,
4143 "No target-specific reset for %s",
4144 target->cmd_name);
4145 return JIM_ERR;
4147 /* determine if we should halt or not. */
4148 target->reset_halt = !!a;
4149 /* When this happens - all workareas are invalid. */
4150 target_free_all_working_areas_restore(target, 0);
4152 /* do the assert */
4153 if (n->value == NVP_ASSERT) {
4154 e = target->type->assert_reset(target);
4155 } else {
4156 e = target->type->deassert_reset(target);
4158 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4159 case TS_CMD_HALT:
4160 if (goi.argc) {
4161 Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4162 return JIM_ERR;
4164 if (!target->tap->enabled)
4165 goto err_tap_disabled;
4166 e = target->type->halt(target);
4167 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4168 case TS_CMD_WAITSTATE:
4169 /* params: <name> statename timeoutmsecs */
4170 if (goi.argc != 2) {
4171 Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4172 return JIM_ERR;
4174 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4175 if (e != JIM_OK) {
4176 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4177 return e;
4179 e = Jim_GetOpt_Wide(&goi, &a);
4180 if (e != JIM_OK) {
4181 return e;
4183 if (!target->tap->enabled)
4184 goto err_tap_disabled;
4185 e = target_wait_state(target, n->value, a);
4186 if (e != ERROR_OK) {
4187 Jim_SetResult_sprintf(goi.interp,
4188 "target: %s wait %s fails (%d) %s",
4189 target->cmd_name,
4190 n->name,
4191 e, target_strerror_safe(e));
4192 return JIM_ERR;
4193 } else {
4194 return JIM_OK;
4196 case TS_CMD_EVENTLIST:
4197 /* List for human, Events defined for this target.
4198 * scripts/programs should use 'name cget -event NAME'
4201 target_event_action_t *teap;
4202 teap = target->event_action;
4203 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4204 target->target_number,
4205 target->cmd_name);
4206 command_print(cmd_ctx, "%-25s | Body", "Event");
4207 command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4208 while (teap) {
4209 command_print(cmd_ctx,
4210 "%-25s | %s",
4211 Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4212 Jim_GetString(teap->body, NULL));
4213 teap = teap->next;
4215 command_print(cmd_ctx, "***END***");
4216 return JIM_OK;
4218 case TS_CMD_CURSTATE:
4219 if (goi.argc != 0) {
4220 Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4221 return JIM_ERR;
4223 Jim_SetResultString(goi.interp,
4224 target_state_name( target ),
4225 -1);
4226 return JIM_OK;
4227 case TS_CMD_INVOKE_EVENT:
4228 if (goi.argc != 1) {
4229 Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4230 return JIM_ERR;
4232 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4233 if (e != JIM_OK) {
4234 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4235 return e;
4237 target_handle_event(target, n->value);
4238 return JIM_OK;
4240 return JIM_ERR;
4242 err_tap_disabled:
4243 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4244 return JIM_ERR;
4247 static int target_create(Jim_GetOptInfo *goi)
4249 Jim_Obj *new_cmd;
4250 Jim_Cmd *cmd;
4251 const char *cp;
4252 char *cp2;
4253 int e;
4254 int x;
4255 target_t *target;
4256 struct command_context_s *cmd_ctx;
4258 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4259 if (goi->argc < 3) {
4260 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4261 return JIM_ERR;
4264 /* COMMAND */
4265 Jim_GetOpt_Obj(goi, &new_cmd);
4266 /* does this command exist? */
4267 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4268 if (cmd) {
4269 cp = Jim_GetString(new_cmd, NULL);
4270 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4271 return JIM_ERR;
4274 /* TYPE */
4275 e = Jim_GetOpt_String(goi, &cp2, NULL);
4276 cp = cp2;
4277 /* now does target type exist */
4278 for (x = 0 ; target_types[x] ; x++) {
4279 if (0 == strcmp(cp, target_types[x]->name)) {
4280 /* found */
4281 break;
4284 if (target_types[x] == NULL) {
4285 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4286 for (x = 0 ; target_types[x] ; x++) {
4287 if (target_types[x + 1]) {
4288 Jim_AppendStrings(goi->interp,
4289 Jim_GetResult(goi->interp),
4290 target_types[x]->name,
4291 ", ", NULL);
4292 } else {
4293 Jim_AppendStrings(goi->interp,
4294 Jim_GetResult(goi->interp),
4295 " or ",
4296 target_types[x]->name,NULL);
4299 return JIM_ERR;
4302 /* Create it */
4303 target = calloc(1,sizeof(target_t));
4304 /* set target number */
4305 target->target_number = new_target_number();
4307 /* allocate memory for each unique target type */
4308 target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4310 memcpy(target->type, target_types[x], sizeof(target_type_t));
4312 /* will be set by "-endian" */
4313 target->endianness = TARGET_ENDIAN_UNKNOWN;
4315 target->working_area = 0x0;
4316 target->working_area_size = 0x0;
4317 target->working_areas = NULL;
4318 target->backup_working_area = 0;
4320 target->state = TARGET_UNKNOWN;
4321 target->debug_reason = DBG_REASON_UNDEFINED;
4322 target->reg_cache = NULL;
4323 target->breakpoints = NULL;
4324 target->watchpoints = NULL;
4325 target->next = NULL;
4326 target->arch_info = NULL;
4328 target->display = 1;
4330 target->halt_issued = false;
4332 /* initialize trace information */
4333 target->trace_info = malloc(sizeof(trace_t));
4334 target->trace_info->num_trace_points = 0;
4335 target->trace_info->trace_points_size = 0;
4336 target->trace_info->trace_points = NULL;
4337 target->trace_info->trace_history_size = 0;
4338 target->trace_info->trace_history = NULL;
4339 target->trace_info->trace_history_pos = 0;
4340 target->trace_info->trace_history_overflowed = 0;
4342 target->dbgmsg = NULL;
4343 target->dbg_msg_enabled = 0;
4345 target->endianness = TARGET_ENDIAN_UNKNOWN;
4347 /* Do the rest as "configure" options */
4348 goi->isconfigure = 1;
4349 e = target_configure(goi, target);
4351 if (target->tap == NULL)
4353 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4354 e = JIM_ERR;
4357 if (e != JIM_OK) {
4358 free(target->type);
4359 free(target);
4360 return e;
4363 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4364 /* default endian to little if not specified */
4365 target->endianness = TARGET_LITTLE_ENDIAN;
4368 /* incase variant is not set */
4369 if (!target->variant)
4370 target->variant = strdup("");
4372 /* create the target specific commands */
4373 if (target->type->register_commands) {
4374 (*(target->type->register_commands))(cmd_ctx);
4376 if (target->type->target_create) {
4377 (*(target->type->target_create))(target, goi->interp);
4380 /* append to end of list */
4382 target_t **tpp;
4383 tpp = &(all_targets);
4384 while (*tpp) {
4385 tpp = &((*tpp)->next);
4387 *tpp = target;
4390 cp = Jim_GetString(new_cmd, NULL);
4391 target->cmd_name = strdup(cp);
4393 /* now - create the new target name command */
4394 e = Jim_CreateCommand(goi->interp,
4395 /* name */
4397 tcl_target_func, /* C function */
4398 target, /* private data */
4399 NULL); /* no del proc */
4401 return e;
4404 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4406 int x,r,e;
4407 jim_wide w;
4408 struct command_context_s *cmd_ctx;
4409 target_t *target;
4410 Jim_GetOptInfo goi;
4411 enum tcmd {
4412 /* TG = target generic */
4413 TG_CMD_CREATE,
4414 TG_CMD_TYPES,
4415 TG_CMD_NAMES,
4416 TG_CMD_CURRENT,
4417 TG_CMD_NUMBER,
4418 TG_CMD_COUNT,
4420 const char *target_cmds[] = {
4421 "create", "types", "names", "current", "number",
4422 "count",
4423 NULL /* terminate */
4426 LOG_DEBUG("Target command params:");
4427 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4429 cmd_ctx = Jim_GetAssocData(interp, "context");
4431 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4433 if (goi.argc == 0) {
4434 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4435 return JIM_ERR;
4438 /* Jim_GetOpt_Debug(&goi); */
4439 r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4440 if (r != JIM_OK) {
4441 return r;
4444 switch (x) {
4445 default:
4446 Jim_Panic(goi.interp,"Why am I here?");
4447 return JIM_ERR;
4448 case TG_CMD_CURRENT:
4449 if (goi.argc != 0) {
4450 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4451 return JIM_ERR;
4453 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4454 return JIM_OK;
4455 case TG_CMD_TYPES:
4456 if (goi.argc != 0) {
4457 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4458 return JIM_ERR;
4460 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4461 for (x = 0 ; target_types[x] ; x++) {
4462 Jim_ListAppendElement(goi.interp,
4463 Jim_GetResult(goi.interp),
4464 Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4466 return JIM_OK;
4467 case TG_CMD_NAMES:
4468 if (goi.argc != 0) {
4469 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4470 return JIM_ERR;
4472 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4473 target = all_targets;
4474 while (target) {
4475 Jim_ListAppendElement(goi.interp,
4476 Jim_GetResult(goi.interp),
4477 Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4478 target = target->next;
4480 return JIM_OK;
4481 case TG_CMD_CREATE:
4482 if (goi.argc < 3) {
4483 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4484 return JIM_ERR;
4486 return target_create(&goi);
4487 break;
4488 case TG_CMD_NUMBER:
4489 /* It's OK to remove this mechanism sometime after August 2010 or so */
4490 LOG_WARNING("don't use numbers as target identifiers; use names");
4491 if (goi.argc != 1) {
4492 Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4493 return JIM_ERR;
4495 e = Jim_GetOpt_Wide(&goi, &w);
4496 if (e != JIM_OK) {
4497 return JIM_ERR;
4499 for (x = 0, target = all_targets; target; target = target->next, x++) {
4500 if (target->target_number == w)
4501 break;
4503 if (target == NULL) {
4504 Jim_SetResult_sprintf(goi.interp,
4505 "Target: number %d does not exist", (int)(w));
4506 return JIM_ERR;
4508 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4509 return JIM_OK;
4510 case TG_CMD_COUNT:
4511 if (goi.argc != 0) {
4512 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4513 return JIM_ERR;
4515 for (x = 0, target = all_targets; target; target = target->next, x++)
4516 continue;
4517 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4518 return JIM_OK;
4521 return JIM_ERR;
4525 struct FastLoad
4527 uint32_t address;
4528 uint8_t *data;
4529 int length;
4533 static int fastload_num;
4534 static struct FastLoad *fastload;
4536 static void free_fastload(void)
4538 if (fastload != NULL)
4540 int i;
4541 for (i = 0; i < fastload_num; i++)
4543 if (fastload[i].data)
4544 free(fastload[i].data);
4546 free(fastload);
4547 fastload = NULL;
4554 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4556 uint8_t *buffer;
4557 uint32_t buf_cnt;
4558 uint32_t image_size;
4559 uint32_t min_address = 0;
4560 uint32_t max_address = 0xffffffff;
4561 int i;
4563 image_t image;
4565 duration_t duration;
4566 char *duration_text;
4568 int retval = parse_load_image_command_args(args, argc,
4569 &image, &min_address, &max_address);
4570 if (ERROR_OK != retval)
4571 return retval;
4573 duration_start_measure(&duration);
4575 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4577 return ERROR_OK;
4580 image_size = 0x0;
4581 retval = ERROR_OK;
4582 fastload_num = image.num_sections;
4583 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4584 if (fastload == NULL)
4586 image_close(&image);
4587 return ERROR_FAIL;
4589 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4590 for (i = 0; i < image.num_sections; i++)
4592 buffer = malloc(image.sections[i].size);
4593 if (buffer == NULL)
4595 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4596 (int)(image.sections[i].size));
4597 break;
4600 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4602 free(buffer);
4603 break;
4606 uint32_t offset = 0;
4607 uint32_t length = buf_cnt;
4610 /* DANGER!!! beware of unsigned comparision here!!! */
4612 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4613 (image.sections[i].base_address < max_address))
4615 if (image.sections[i].base_address < min_address)
4617 /* clip addresses below */
4618 offset += min_address-image.sections[i].base_address;
4619 length -= offset;
4622 if (image.sections[i].base_address + buf_cnt > max_address)
4624 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4627 fastload[i].address = image.sections[i].base_address + offset;
4628 fastload[i].data = malloc(length);
4629 if (fastload[i].data == NULL)
4631 free(buffer);
4632 break;
4634 memcpy(fastload[i].data, buffer + offset, length);
4635 fastload[i].length = length;
4637 image_size += length;
4638 command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4639 (unsigned int)length,
4640 ((unsigned int)(image.sections[i].base_address + offset)));
4643 free(buffer);
4646 duration_stop_measure(&duration, &duration_text);
4647 if (retval == ERROR_OK)
4649 command_print(cmd_ctx, "Loaded %u bytes in %s", (unsigned int)image_size, duration_text);
4650 command_print(cmd_ctx, "NB!!! image has not been loaded to target, issue a subsequent 'fast_load' to do so.");
4652 free(duration_text);
4654 image_close(&image);
4656 if (retval != ERROR_OK)
4658 free_fastload();
4661 return retval;
4664 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4666 if (argc > 0)
4667 return ERROR_COMMAND_SYNTAX_ERROR;
4668 if (fastload == NULL)
4670 LOG_ERROR("No image in memory");
4671 return ERROR_FAIL;
4673 int i;
4674 int ms = timeval_ms();
4675 int size = 0;
4676 int retval = ERROR_OK;
4677 for (i = 0; i < fastload_num;i++)
4679 target_t *target = get_current_target(cmd_ctx);
4680 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4681 (unsigned int)(fastload[i].address),
4682 (unsigned int)(fastload[i].length));
4683 if (retval == ERROR_OK)
4685 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4687 size += fastload[i].length;
4689 int after = timeval_ms();
4690 command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4691 return retval;
4696 * Local Variables:
4697 * c-basic-offset: 4
4698 * tab-width: 4
4699 * End: