Fw: [PATCH] OpenRD board configuration
[openocd/cortex.git] / src / target / target.c
blob7763b95644d65d3dfce0d86e39e65e43dbde5112
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_write_memory(struct target_s *target,
605 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
607 return target->type->write_memory(target, address, size, count, buffer);
609 int target_bulk_write_memory(struct target_s *target,
610 uint32_t address, uint32_t count, uint8_t *buffer)
612 return target->type->bulk_write_memory(target, address, count, buffer);
615 int target_add_breakpoint(struct target_s *target,
616 struct breakpoint_s *breakpoint)
618 return target->type->add_breakpoint(target, breakpoint);
620 int target_remove_breakpoint(struct target_s *target,
621 struct breakpoint_s *breakpoint)
623 return target->type->remove_breakpoint(target, breakpoint);
626 int target_add_watchpoint(struct target_s *target,
627 struct watchpoint_s *watchpoint)
629 return target->type->add_watchpoint(target, watchpoint);
631 int target_remove_watchpoint(struct target_s *target,
632 struct watchpoint_s *watchpoint)
634 return target->type->remove_watchpoint(target, watchpoint);
637 int target_get_gdb_reg_list(struct target_s *target,
638 struct reg_s **reg_list[], int *reg_list_size)
640 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
642 int target_step(struct target_s *target,
643 int current, uint32_t address, int handle_breakpoints)
645 return target->type->step(target, current, address, handle_breakpoints);
649 int target_run_algorithm(struct target_s *target,
650 int num_mem_params, mem_param_t *mem_params,
651 int num_reg_params, reg_param_t *reg_param,
652 uint32_t entry_point, uint32_t exit_point,
653 int timeout_ms, void *arch_info)
655 return target->type->run_algorithm(target,
656 num_mem_params, mem_params, num_reg_params, reg_param,
657 entry_point, exit_point, timeout_ms, arch_info);
660 /// @returns @c true if the target has been examined.
661 bool target_was_examined(struct target_s *target)
663 return target->type->examined;
665 /// Sets the @c examined flag for the given target.
666 void target_set_examined(struct target_s *target)
668 target->type->examined = true;
670 // Reset the @c examined flag for the given target.
671 void target_reset_examined(struct target_s *target)
673 target->type->examined = false;
677 int target_init(struct command_context_s *cmd_ctx)
679 target_t *target = all_targets;
680 int retval;
682 while (target)
684 target_reset_examined(target);
685 if (target->type->examine == NULL)
687 target->type->examine = default_examine;
690 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
692 LOG_ERROR("target '%s' init failed", target_get_name(target));
693 return retval;
696 /* Set up default functions if none are provided by target */
697 if (target->type->virt2phys == NULL)
699 target->type->virt2phys = default_virt2phys;
701 /* a non-invasive way(in terms of patches) to add some code that
702 * runs before the type->write/read_memory implementation
704 target->type->write_memory_imp = target->type->write_memory;
705 target->type->write_memory = target_write_memory_imp;
706 target->type->read_memory_imp = target->type->read_memory;
707 target->type->read_memory = target_read_memory_imp;
708 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
709 target->type->soft_reset_halt = target_soft_reset_halt_imp;
710 target->type->run_algorithm_imp = target->type->run_algorithm;
711 target->type->run_algorithm = target_run_algorithm_imp;
713 if (target->type->mmu == NULL)
715 target->type->mmu = default_mmu;
717 target = target->next;
720 if (all_targets)
722 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
723 return retval;
724 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
725 return retval;
728 return ERROR_OK;
731 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
733 target_event_callback_t **callbacks_p = &target_event_callbacks;
735 if (callback == NULL)
737 return ERROR_INVALID_ARGUMENTS;
740 if (*callbacks_p)
742 while ((*callbacks_p)->next)
743 callbacks_p = &((*callbacks_p)->next);
744 callbacks_p = &((*callbacks_p)->next);
747 (*callbacks_p) = malloc(sizeof(target_event_callback_t));
748 (*callbacks_p)->callback = callback;
749 (*callbacks_p)->priv = priv;
750 (*callbacks_p)->next = NULL;
752 return ERROR_OK;
755 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
757 target_timer_callback_t **callbacks_p = &target_timer_callbacks;
758 struct timeval now;
760 if (callback == NULL)
762 return ERROR_INVALID_ARGUMENTS;
765 if (*callbacks_p)
767 while ((*callbacks_p)->next)
768 callbacks_p = &((*callbacks_p)->next);
769 callbacks_p = &((*callbacks_p)->next);
772 (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
773 (*callbacks_p)->callback = callback;
774 (*callbacks_p)->periodic = periodic;
775 (*callbacks_p)->time_ms = time_ms;
777 gettimeofday(&now, NULL);
778 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
779 time_ms -= (time_ms % 1000);
780 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
781 if ((*callbacks_p)->when.tv_usec > 1000000)
783 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
784 (*callbacks_p)->when.tv_sec += 1;
787 (*callbacks_p)->priv = priv;
788 (*callbacks_p)->next = NULL;
790 return ERROR_OK;
793 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
795 target_event_callback_t **p = &target_event_callbacks;
796 target_event_callback_t *c = target_event_callbacks;
798 if (callback == NULL)
800 return ERROR_INVALID_ARGUMENTS;
803 while (c)
805 target_event_callback_t *next = c->next;
806 if ((c->callback == callback) && (c->priv == priv))
808 *p = next;
809 free(c);
810 return ERROR_OK;
812 else
813 p = &(c->next);
814 c = next;
817 return ERROR_OK;
820 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
822 target_timer_callback_t **p = &target_timer_callbacks;
823 target_timer_callback_t *c = target_timer_callbacks;
825 if (callback == NULL)
827 return ERROR_INVALID_ARGUMENTS;
830 while (c)
832 target_timer_callback_t *next = c->next;
833 if ((c->callback == callback) && (c->priv == priv))
835 *p = next;
836 free(c);
837 return ERROR_OK;
839 else
840 p = &(c->next);
841 c = next;
844 return ERROR_OK;
847 int target_call_event_callbacks(target_t *target, enum target_event event)
849 target_event_callback_t *callback = target_event_callbacks;
850 target_event_callback_t *next_callback;
852 if (event == TARGET_EVENT_HALTED)
854 /* execute early halted first */
855 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
858 LOG_DEBUG("target event %i (%s)",
859 event,
860 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
862 target_handle_event(target, event);
864 while (callback)
866 next_callback = callback->next;
867 callback->callback(target, event, callback->priv);
868 callback = next_callback;
871 return ERROR_OK;
874 static int target_timer_callback_periodic_restart(
875 target_timer_callback_t *cb, struct timeval *now)
877 int time_ms = cb->time_ms;
878 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
879 time_ms -= (time_ms % 1000);
880 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
881 if (cb->when.tv_usec > 1000000)
883 cb->when.tv_usec = cb->when.tv_usec - 1000000;
884 cb->when.tv_sec += 1;
886 return ERROR_OK;
889 static int target_call_timer_callback(target_timer_callback_t *cb,
890 struct timeval *now)
892 cb->callback(cb->priv);
894 if (cb->periodic)
895 return target_timer_callback_periodic_restart(cb, now);
897 return target_unregister_timer_callback(cb->callback, cb->priv);
900 static int target_call_timer_callbacks_check_time(int checktime)
902 keep_alive();
904 struct timeval now;
905 gettimeofday(&now, NULL);
907 target_timer_callback_t *callback = target_timer_callbacks;
908 while (callback)
910 // cleaning up may unregister and free this callback
911 target_timer_callback_t *next_callback = callback->next;
913 bool call_it = callback->callback &&
914 ((!checktime && callback->periodic) ||
915 now.tv_sec > callback->when.tv_sec ||
916 (now.tv_sec == callback->when.tv_sec &&
917 now.tv_usec >= callback->when.tv_usec));
919 if (call_it)
921 int retval = target_call_timer_callback(callback, &now);
922 if (retval != ERROR_OK)
923 return retval;
926 callback = next_callback;
929 return ERROR_OK;
932 int target_call_timer_callbacks(void)
934 return target_call_timer_callbacks_check_time(1);
937 /* invoke periodic callbacks immediately */
938 int target_call_timer_callbacks_now(void)
940 return target_call_timer_callbacks_check_time(0);
943 int target_alloc_working_area(struct target_s *target, uint32_t size, working_area_t **area)
945 working_area_t *c = target->working_areas;
946 working_area_t *new_wa = NULL;
948 /* Reevaluate working area address based on MMU state*/
949 if (target->working_areas == NULL)
951 int retval;
952 int enabled;
953 retval = target->type->mmu(target, &enabled);
954 if (retval != ERROR_OK)
956 return retval;
958 if (enabled)
960 target->working_area = target->working_area_virt;
962 else
964 target->working_area = target->working_area_phys;
968 /* only allocate multiples of 4 byte */
969 if (size % 4)
971 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
972 size = (size + 3) & (~3);
975 /* see if there's already a matching working area */
976 while (c)
978 if ((c->free) && (c->size == size))
980 new_wa = c;
981 break;
983 c = c->next;
986 /* if not, allocate a new one */
987 if (!new_wa)
989 working_area_t **p = &target->working_areas;
990 uint32_t first_free = target->working_area;
991 uint32_t free_size = target->working_area_size;
993 LOG_DEBUG("allocating new working area");
995 c = target->working_areas;
996 while (c)
998 first_free += c->size;
999 free_size -= c->size;
1000 p = &c->next;
1001 c = c->next;
1004 if (free_size < size)
1006 LOG_WARNING("not enough working area available(requested %u, free %u)",
1007 (unsigned)(size), (unsigned)(free_size));
1008 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1011 new_wa = malloc(sizeof(working_area_t));
1012 new_wa->next = NULL;
1013 new_wa->size = size;
1014 new_wa->address = first_free;
1016 if (target->backup_working_area)
1018 int retval;
1019 new_wa->backup = malloc(new_wa->size);
1020 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1022 free(new_wa->backup);
1023 free(new_wa);
1024 return retval;
1027 else
1029 new_wa->backup = NULL;
1032 /* put new entry in list */
1033 *p = new_wa;
1036 /* mark as used, and return the new (reused) area */
1037 new_wa->free = 0;
1038 *area = new_wa;
1040 /* user pointer */
1041 new_wa->user = area;
1043 return ERROR_OK;
1046 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
1048 if (area->free)
1049 return ERROR_OK;
1051 if (restore && target->backup_working_area)
1053 int retval;
1054 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1055 return retval;
1058 area->free = 1;
1060 /* mark user pointer invalid */
1061 *area->user = NULL;
1062 area->user = NULL;
1064 return ERROR_OK;
1067 int target_free_working_area(struct target_s *target, working_area_t *area)
1069 return target_free_working_area_restore(target, area, 1);
1072 /* free resources and restore memory, if restoring memory fails,
1073 * free up resources anyway
1075 void target_free_all_working_areas_restore(struct target_s *target, int restore)
1077 working_area_t *c = target->working_areas;
1079 while (c)
1081 working_area_t *next = c->next;
1082 target_free_working_area_restore(target, c, restore);
1084 if (c->backup)
1085 free(c->backup);
1087 free(c);
1089 c = next;
1092 target->working_areas = NULL;
1095 void target_free_all_working_areas(struct target_s *target)
1097 target_free_all_working_areas_restore(target, 1);
1100 int target_register_commands(struct command_context_s *cmd_ctx)
1103 register_command(cmd_ctx, NULL, "targets", handle_targets_command, COMMAND_EXEC, "change the current command line target (one parameter) or lists targets (with no parameter)");
1108 register_jim(cmd_ctx, "target", jim_target, "configure target");
1110 return ERROR_OK;
1113 int target_arch_state(struct target_s *target)
1115 int retval;
1116 if (target == NULL)
1118 LOG_USER("No target has been configured");
1119 return ERROR_OK;
1122 LOG_USER("target state: %s", target_state_name( target ));
1124 if (target->state != TARGET_HALTED)
1125 return ERROR_OK;
1127 retval = target->type->arch_state(target);
1128 return retval;
1131 /* Single aligned words are guaranteed to use 16 or 32 bit access
1132 * mode respectively, otherwise data is handled as quickly as
1133 * possible
1135 int target_write_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1137 int retval;
1138 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1139 (int)size, (unsigned)address);
1141 if (!target_was_examined(target))
1143 LOG_ERROR("Target not examined yet");
1144 return ERROR_FAIL;
1147 if (size == 0) {
1148 return ERROR_OK;
1151 if ((address + size - 1) < address)
1153 /* GDB can request this when e.g. PC is 0xfffffffc*/
1154 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1155 (unsigned)address,
1156 (unsigned)size);
1157 return ERROR_FAIL;
1160 if (((address % 2) == 0) && (size == 2))
1162 return target_write_memory(target, address, 2, 1, buffer);
1165 /* handle unaligned head bytes */
1166 if (address % 4)
1168 uint32_t unaligned = 4 - (address % 4);
1170 if (unaligned > size)
1171 unaligned = size;
1173 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1174 return retval;
1176 buffer += unaligned;
1177 address += unaligned;
1178 size -= unaligned;
1181 /* handle aligned words */
1182 if (size >= 4)
1184 int aligned = size - (size % 4);
1186 /* use bulk writes above a certain limit. This may have to be changed */
1187 if (aligned > 128)
1189 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1190 return retval;
1192 else
1194 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1195 return retval;
1198 buffer += aligned;
1199 address += aligned;
1200 size -= aligned;
1203 /* handle tail writes of less than 4 bytes */
1204 if (size > 0)
1206 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1207 return retval;
1210 return ERROR_OK;
1213 /* Single aligned words are guaranteed to use 16 or 32 bit access
1214 * mode respectively, otherwise data is handled as quickly as
1215 * possible
1217 int target_read_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1219 int retval;
1220 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1221 (int)size, (unsigned)address);
1223 if (!target_was_examined(target))
1225 LOG_ERROR("Target not examined yet");
1226 return ERROR_FAIL;
1229 if (size == 0) {
1230 return ERROR_OK;
1233 if ((address + size - 1) < address)
1235 /* GDB can request this when e.g. PC is 0xfffffffc*/
1236 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1237 address,
1238 size);
1239 return ERROR_FAIL;
1242 if (((address % 2) == 0) && (size == 2))
1244 return target_read_memory(target, address, 2, 1, buffer);
1247 /* handle unaligned head bytes */
1248 if (address % 4)
1250 uint32_t unaligned = 4 - (address % 4);
1252 if (unaligned > size)
1253 unaligned = size;
1255 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1256 return retval;
1258 buffer += unaligned;
1259 address += unaligned;
1260 size -= unaligned;
1263 /* handle aligned words */
1264 if (size >= 4)
1266 int aligned = size - (size % 4);
1268 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1269 return retval;
1271 buffer += aligned;
1272 address += aligned;
1273 size -= aligned;
1276 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1277 if(size >=2)
1279 int aligned = size - (size%2);
1280 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1281 if (retval != ERROR_OK)
1282 return retval;
1284 buffer += aligned;
1285 address += aligned;
1286 size -= aligned;
1288 /* handle tail writes of less than 4 bytes */
1289 if (size > 0)
1291 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1292 return retval;
1295 return ERROR_OK;
1298 int target_checksum_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* crc)
1300 uint8_t *buffer;
1301 int retval;
1302 uint32_t i;
1303 uint32_t checksum = 0;
1304 if (!target_was_examined(target))
1306 LOG_ERROR("Target not examined yet");
1307 return ERROR_FAIL;
1310 if ((retval = target->type->checksum_memory(target, address,
1311 size, &checksum)) != ERROR_OK)
1313 buffer = malloc(size);
1314 if (buffer == NULL)
1316 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1317 return ERROR_INVALID_ARGUMENTS;
1319 retval = target_read_buffer(target, address, size, buffer);
1320 if (retval != ERROR_OK)
1322 free(buffer);
1323 return retval;
1326 /* convert to target endianess */
1327 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1329 uint32_t target_data;
1330 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1331 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1334 retval = image_calculate_checksum(buffer, size, &checksum);
1335 free(buffer);
1338 *crc = checksum;
1340 return retval;
1343 int target_blank_check_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* blank)
1345 int retval;
1346 if (!target_was_examined(target))
1348 LOG_ERROR("Target not examined yet");
1349 return ERROR_FAIL;
1352 if (target->type->blank_check_memory == 0)
1353 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1355 retval = target->type->blank_check_memory(target, address, size, blank);
1357 return retval;
1360 int target_read_u32(struct target_s *target, uint32_t address, uint32_t *value)
1362 uint8_t value_buf[4];
1363 if (!target_was_examined(target))
1365 LOG_ERROR("Target not examined yet");
1366 return ERROR_FAIL;
1369 int retval = target_read_memory(target, address, 4, 1, value_buf);
1371 if (retval == ERROR_OK)
1373 *value = target_buffer_get_u32(target, value_buf);
1374 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1375 address,
1376 *value);
1378 else
1380 *value = 0x0;
1381 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1382 address);
1385 return retval;
1388 int target_read_u16(struct target_s *target, uint32_t address, uint16_t *value)
1390 uint8_t value_buf[2];
1391 if (!target_was_examined(target))
1393 LOG_ERROR("Target not examined yet");
1394 return ERROR_FAIL;
1397 int retval = target_read_memory(target, address, 2, 1, value_buf);
1399 if (retval == ERROR_OK)
1401 *value = target_buffer_get_u16(target, value_buf);
1402 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1403 address,
1404 *value);
1406 else
1408 *value = 0x0;
1409 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1410 address);
1413 return retval;
1416 int target_read_u8(struct target_s *target, uint32_t address, uint8_t *value)
1418 int retval = target_read_memory(target, address, 1, 1, value);
1419 if (!target_was_examined(target))
1421 LOG_ERROR("Target not examined yet");
1422 return ERROR_FAIL;
1425 if (retval == ERROR_OK)
1427 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1428 address,
1429 *value);
1431 else
1433 *value = 0x0;
1434 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1435 address);
1438 return retval;
1441 int target_write_u32(struct target_s *target, uint32_t address, uint32_t value)
1443 int retval;
1444 uint8_t value_buf[4];
1445 if (!target_was_examined(target))
1447 LOG_ERROR("Target not examined yet");
1448 return ERROR_FAIL;
1451 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1452 address,
1453 value);
1455 target_buffer_set_u32(target, value_buf, value);
1456 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1458 LOG_DEBUG("failed: %i", retval);
1461 return retval;
1464 int target_write_u16(struct target_s *target, uint32_t address, uint16_t value)
1466 int retval;
1467 uint8_t value_buf[2];
1468 if (!target_was_examined(target))
1470 LOG_ERROR("Target not examined yet");
1471 return ERROR_FAIL;
1474 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1475 address,
1476 value);
1478 target_buffer_set_u16(target, value_buf, value);
1479 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1481 LOG_DEBUG("failed: %i", retval);
1484 return retval;
1487 int target_write_u8(struct target_s *target, uint32_t address, uint8_t value)
1489 int retval;
1490 if (!target_was_examined(target))
1492 LOG_ERROR("Target not examined yet");
1493 return ERROR_FAIL;
1496 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1497 address, value);
1499 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1501 LOG_DEBUG("failed: %i", retval);
1504 return retval;
1507 int target_register_user_commands(struct command_context_s *cmd_ctx)
1509 int retval = ERROR_OK;
1512 /* script procedures */
1513 register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "profiling samples the CPU PC");
1514 register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array, "read memory and return as a TCL array for script processing <ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
1515 register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem, "convert a TCL array to memory locations and write the values <ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
1517 register_command(cmd_ctx, NULL, "fast_load_image", handle_fast_load_image_command, COMMAND_ANY,
1518 "same args as load_image, image stored in memory - mainly for profiling purposes");
1520 register_command(cmd_ctx, NULL, "fast_load", handle_fast_load_command, COMMAND_ANY,
1521 "loads active fast load image to current target - mainly for profiling purposes");
1524 register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "translate a virtual address into a physical address");
1525 register_command(cmd_ctx, NULL, "reg", handle_reg_command, COMMAND_EXEC, "display or set a register");
1526 register_command(cmd_ctx, NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1527 register_command(cmd_ctx, NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1528 register_command(cmd_ctx, NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1529 register_command(cmd_ctx, NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1530 register_command(cmd_ctx, NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1531 register_command(cmd_ctx, NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run | halt | init] - default is run");
1532 register_command(cmd_ctx, NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1534 register_command(cmd_ctx, NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words <addr> [count]");
1535 register_command(cmd_ctx, NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words <addr> [count]");
1536 register_command(cmd_ctx, NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes <addr> [count]");
1538 register_command(cmd_ctx, NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word <addr> <value> [count]");
1539 register_command(cmd_ctx, NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word <addr> <value> [count]");
1540 register_command(cmd_ctx, NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte <addr> <value> [count]");
1542 register_command(cmd_ctx, NULL, "bp",
1543 handle_bp_command, COMMAND_EXEC,
1544 "list or set breakpoint [<address> <length> [hw]]");
1545 register_command(cmd_ctx, NULL, "rbp",
1546 handle_rbp_command, COMMAND_EXEC,
1547 "remove breakpoint <address>");
1548 register_command(cmd_ctx, NULL, "wp",
1549 handle_wp_command, COMMAND_EXEC,
1550 "list or set watchpoint "
1551 "[<address> <length> <r/w/a> [value] [mask]]");
1552 register_command(cmd_ctx, NULL, "rwp",
1553 handle_rwp_command, COMMAND_EXEC,
1554 "remove watchpoint <address>");
1556 register_command(cmd_ctx, NULL, "load_image", handle_load_image_command, COMMAND_EXEC, "load_image <file> <address> ['bin'|'ihex'|'elf'|'s19'] [min_address] [max_length]");
1557 register_command(cmd_ctx, NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1558 register_command(cmd_ctx, NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1559 register_command(cmd_ctx, NULL, "test_image", handle_test_image_command, COMMAND_EXEC, "test_image <file> [offset] [type]");
1561 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
1562 return retval;
1563 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
1564 return retval;
1566 return retval;
1569 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1571 target_t *target = all_targets;
1573 if (argc == 1)
1575 target = get_target(args[0]);
1576 if (target == NULL) {
1577 command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1578 goto DumpTargets;
1580 if (!target->tap->enabled) {
1581 command_print(cmd_ctx,"Target: TAP %s is disabled, "
1582 "can't be the current target\n",
1583 target->tap->dotted_name);
1584 return ERROR_FAIL;
1587 cmd_ctx->current_target = target->target_number;
1588 return ERROR_OK;
1590 DumpTargets:
1592 target = all_targets;
1593 command_print(cmd_ctx, " TargetName Type Endian TapName State ");
1594 command_print(cmd_ctx, "-- ------------------ ---------- ------ ------------------ ------------");
1595 while (target)
1597 const char *state;
1598 char marker = ' ';
1600 if (target->tap->enabled)
1601 state = target_state_name( target );
1602 else
1603 state = "tap-disabled";
1605 if (cmd_ctx->current_target == target->target_number)
1606 marker = '*';
1608 /* keep columns lined up to match the headers above */
1609 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1610 target->target_number,
1611 marker,
1612 target->cmd_name,
1613 target_get_name(target),
1614 Jim_Nvp_value2name_simple(nvp_target_endian,
1615 target->endianness)->name,
1616 target->tap->dotted_name,
1617 state);
1618 target = target->next;
1621 return ERROR_OK;
1624 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1626 static int powerDropout;
1627 static int srstAsserted;
1629 static int runPowerRestore;
1630 static int runPowerDropout;
1631 static int runSrstAsserted;
1632 static int runSrstDeasserted;
1634 static int sense_handler(void)
1636 static int prevSrstAsserted = 0;
1637 static int prevPowerdropout = 0;
1639 int retval;
1640 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1641 return retval;
1643 int powerRestored;
1644 powerRestored = prevPowerdropout && !powerDropout;
1645 if (powerRestored)
1647 runPowerRestore = 1;
1650 long long current = timeval_ms();
1651 static long long lastPower = 0;
1652 int waitMore = lastPower + 2000 > current;
1653 if (powerDropout && !waitMore)
1655 runPowerDropout = 1;
1656 lastPower = current;
1659 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1660 return retval;
1662 int srstDeasserted;
1663 srstDeasserted = prevSrstAsserted && !srstAsserted;
1665 static long long lastSrst = 0;
1666 waitMore = lastSrst + 2000 > current;
1667 if (srstDeasserted && !waitMore)
1669 runSrstDeasserted = 1;
1670 lastSrst = current;
1673 if (!prevSrstAsserted && srstAsserted)
1675 runSrstAsserted = 1;
1678 prevSrstAsserted = srstAsserted;
1679 prevPowerdropout = powerDropout;
1681 if (srstDeasserted || powerRestored)
1683 /* Other than logging the event we can't do anything here.
1684 * Issuing a reset is a particularly bad idea as we might
1685 * be inside a reset already.
1689 return ERROR_OK;
1692 static void target_call_event_callbacks_all(enum target_event e) {
1693 target_t *target;
1694 target = all_targets;
1695 while (target) {
1696 target_call_event_callbacks(target, e);
1697 target = target->next;
1701 /* process target state changes */
1702 int handle_target(void *priv)
1704 int retval = ERROR_OK;
1706 /* we do not want to recurse here... */
1707 static int recursive = 0;
1708 if (! recursive)
1710 recursive = 1;
1711 sense_handler();
1712 /* danger! running these procedures can trigger srst assertions and power dropouts.
1713 * We need to avoid an infinite loop/recursion here and we do that by
1714 * clearing the flags after running these events.
1716 int did_something = 0;
1717 if (runSrstAsserted)
1719 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1720 Jim_Eval(interp, "srst_asserted");
1721 did_something = 1;
1723 if (runSrstDeasserted)
1725 Jim_Eval(interp, "srst_deasserted");
1726 did_something = 1;
1728 if (runPowerDropout)
1730 target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1731 Jim_Eval(interp, "power_dropout");
1732 did_something = 1;
1734 if (runPowerRestore)
1736 Jim_Eval(interp, "power_restore");
1737 did_something = 1;
1740 if (did_something)
1742 /* clear detect flags */
1743 sense_handler();
1746 /* clear action flags */
1748 runSrstAsserted = 0;
1749 runSrstDeasserted = 0;
1750 runPowerRestore = 0;
1751 runPowerDropout = 0;
1753 recursive = 0;
1756 /* Poll targets for state changes unless that's globally disabled.
1757 * Skip targets that are currently disabled.
1759 for (target_t *target = all_targets;
1760 is_jtag_poll_safe() && target;
1761 target = target->next)
1763 if (!target->tap->enabled)
1764 continue;
1766 /* only poll target if we've got power and srst isn't asserted */
1767 if (!powerDropout && !srstAsserted)
1769 /* polling may fail silently until the target has been examined */
1770 if ((retval = target_poll(target)) != ERROR_OK)
1772 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1773 return retval;
1778 return retval;
1781 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1783 target_t *target;
1784 reg_t *reg = NULL;
1785 int count = 0;
1786 char *value;
1788 LOG_DEBUG("-");
1790 target = get_current_target(cmd_ctx);
1792 /* list all available registers for the current target */
1793 if (argc == 0)
1795 reg_cache_t *cache = target->reg_cache;
1797 count = 0;
1798 while (cache)
1800 int i;
1802 for (i = 0, reg = cache->reg_list;
1803 i < cache->num_regs;
1804 i++, reg++, count++)
1806 /* only print cached values if they are valid */
1807 if (reg->valid) {
1808 value = buf_to_str(reg->value,
1809 reg->size, 16);
1810 command_print(cmd_ctx,
1811 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1812 count, reg->name,
1813 reg->size, value,
1814 reg->dirty
1815 ? " (dirty)"
1816 : "");
1817 free(value);
1818 } else {
1819 command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
1820 count, reg->name,
1821 reg->size) ;
1824 cache = cache->next;
1827 return ERROR_OK;
1830 /* access a single register by its ordinal number */
1831 if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1833 unsigned num;
1834 int retval = parse_uint(args[0], &num);
1835 if (ERROR_OK != retval)
1836 return ERROR_COMMAND_SYNTAX_ERROR;
1838 reg_cache_t *cache = target->reg_cache;
1839 count = 0;
1840 while (cache)
1842 int i;
1843 for (i = 0; i < cache->num_regs; i++)
1845 if (count++ == (int)num)
1847 reg = &cache->reg_list[i];
1848 break;
1851 if (reg)
1852 break;
1853 cache = cache->next;
1856 if (!reg)
1858 command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1859 return ERROR_OK;
1861 } else /* access a single register by its name */
1863 reg = register_get_by_name(target->reg_cache, args[0], 1);
1865 if (!reg)
1867 command_print(cmd_ctx, "register %s not found in current target", args[0]);
1868 return ERROR_OK;
1872 /* display a register */
1873 if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1875 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1876 reg->valid = 0;
1878 if (reg->valid == 0)
1880 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1881 arch_type->get(reg);
1883 value = buf_to_str(reg->value, reg->size, 16);
1884 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1885 free(value);
1886 return ERROR_OK;
1889 /* set register value */
1890 if (argc == 2)
1892 uint8_t *buf = malloc(CEIL(reg->size, 8));
1893 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1895 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1896 arch_type->set(reg, buf);
1898 value = buf_to_str(reg->value, reg->size, 16);
1899 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1900 free(value);
1902 free(buf);
1904 return ERROR_OK;
1907 command_print(cmd_ctx, "usage: reg <#|name> [value]");
1909 return ERROR_OK;
1912 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1914 int retval = ERROR_OK;
1915 target_t *target = get_current_target(cmd_ctx);
1917 if (argc == 0)
1919 command_print(cmd_ctx, "background polling: %s",
1920 jtag_poll_get_enabled() ? "on" : "off");
1921 command_print(cmd_ctx, "TAP: %s (%s)",
1922 target->tap->dotted_name,
1923 target->tap->enabled ? "enabled" : "disabled");
1924 if (!target->tap->enabled)
1925 return ERROR_OK;
1926 if ((retval = target_poll(target)) != ERROR_OK)
1927 return retval;
1928 if ((retval = target_arch_state(target)) != ERROR_OK)
1929 return retval;
1932 else if (argc == 1)
1934 if (strcmp(args[0], "on") == 0)
1936 jtag_poll_set_enabled(true);
1938 else if (strcmp(args[0], "off") == 0)
1940 jtag_poll_set_enabled(false);
1942 else
1944 command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1946 } else
1948 return ERROR_COMMAND_SYNTAX_ERROR;
1951 return retval;
1954 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1956 if (argc > 1)
1957 return ERROR_COMMAND_SYNTAX_ERROR;
1959 unsigned ms = 5000;
1960 if (1 == argc)
1962 int retval = parse_uint(args[0], &ms);
1963 if (ERROR_OK != retval)
1965 command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1966 return ERROR_COMMAND_SYNTAX_ERROR;
1968 // convert seconds (given) to milliseconds (needed)
1969 ms *= 1000;
1972 target_t *target = get_current_target(cmd_ctx);
1973 return target_wait_state(target, TARGET_HALTED, ms);
1976 /* wait for target state to change. The trick here is to have a low
1977 * latency for short waits and not to suck up all the CPU time
1978 * on longer waits.
1980 * After 500ms, keep_alive() is invoked
1982 int target_wait_state(target_t *target, enum target_state state, int ms)
1984 int retval;
1985 long long then = 0, cur;
1986 int once = 1;
1988 for (;;)
1990 if ((retval = target_poll(target)) != ERROR_OK)
1991 return retval;
1992 if (target->state == state)
1994 break;
1996 cur = timeval_ms();
1997 if (once)
1999 once = 0;
2000 then = timeval_ms();
2001 LOG_DEBUG("waiting for target %s...",
2002 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2005 if (cur-then > 500)
2007 keep_alive();
2010 if ((cur-then) > ms)
2012 LOG_ERROR("timed out while waiting for target %s",
2013 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2014 return ERROR_FAIL;
2018 return ERROR_OK;
2021 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2023 LOG_DEBUG("-");
2025 target_t *target = get_current_target(cmd_ctx);
2026 int retval = target_halt(target);
2027 if (ERROR_OK != retval)
2028 return retval;
2030 if (argc == 1)
2032 unsigned wait;
2033 retval = parse_uint(args[0], &wait);
2034 if (ERROR_OK != retval)
2035 return ERROR_COMMAND_SYNTAX_ERROR;
2036 if (!wait)
2037 return ERROR_OK;
2040 return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
2043 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2045 target_t *target = get_current_target(cmd_ctx);
2047 LOG_USER("requesting target halt and executing a soft reset");
2049 target->type->soft_reset_halt(target);
2051 return ERROR_OK;
2054 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2056 if (argc > 1)
2057 return ERROR_COMMAND_SYNTAX_ERROR;
2059 enum target_reset_mode reset_mode = RESET_RUN;
2060 if (argc == 1)
2062 const Jim_Nvp *n;
2063 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2064 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2065 return ERROR_COMMAND_SYNTAX_ERROR;
2067 reset_mode = n->value;
2070 /* reset *all* targets */
2071 return target_process_reset(cmd_ctx, reset_mode);
2075 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2077 int current = 1;
2078 if (argc > 1)
2079 return ERROR_COMMAND_SYNTAX_ERROR;
2081 target_t *target = get_current_target(cmd_ctx);
2082 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2084 /* with no args, resume from current pc, addr = 0,
2085 * with one arguments, addr = args[0],
2086 * handle breakpoints, not debugging */
2087 uint32_t addr = 0;
2088 if (argc == 1)
2090 int retval = parse_u32(args[0], &addr);
2091 if (ERROR_OK != retval)
2092 return retval;
2093 current = 0;
2096 return target_resume(target, current, addr, 1, 0);
2099 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2101 if (argc > 1)
2102 return ERROR_COMMAND_SYNTAX_ERROR;
2104 LOG_DEBUG("-");
2106 /* with no args, step from current pc, addr = 0,
2107 * with one argument addr = args[0],
2108 * handle breakpoints, debugging */
2109 uint32_t addr = 0;
2110 int current_pc = 1;
2111 if (argc == 1)
2113 int retval = parse_u32(args[0], &addr);
2114 if (ERROR_OK != retval)
2115 return retval;
2116 current_pc = 0;
2119 target_t *target = get_current_target(cmd_ctx);
2121 return target->type->step(target, current_pc, addr, 1);
2124 static void handle_md_output(struct command_context_s *cmd_ctx,
2125 struct target_s *target, uint32_t address, unsigned size,
2126 unsigned count, const uint8_t *buffer)
2128 const unsigned line_bytecnt = 32;
2129 unsigned line_modulo = line_bytecnt / size;
2131 char output[line_bytecnt * 4 + 1];
2132 unsigned output_len = 0;
2134 const char *value_fmt;
2135 switch (size) {
2136 case 4: value_fmt = "%8.8x "; break;
2137 case 2: value_fmt = "%4.2x "; break;
2138 case 1: value_fmt = "%2.2x "; break;
2139 default:
2140 LOG_ERROR("invalid memory read size: %u", size);
2141 exit(-1);
2144 for (unsigned i = 0; i < count; i++)
2146 if (i % line_modulo == 0)
2148 output_len += snprintf(output + output_len,
2149 sizeof(output) - output_len,
2150 "0x%8.8x: ",
2151 (unsigned)(address + (i*size)));
2154 uint32_t value = 0;
2155 const uint8_t *value_ptr = buffer + i * size;
2156 switch (size) {
2157 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2158 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2159 case 1: value = *value_ptr;
2161 output_len += snprintf(output + output_len,
2162 sizeof(output) - output_len,
2163 value_fmt, value);
2165 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2167 command_print(cmd_ctx, "%s", output);
2168 output_len = 0;
2173 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2175 if (argc < 1)
2176 return ERROR_COMMAND_SYNTAX_ERROR;
2178 unsigned size = 0;
2179 switch (cmd[2]) {
2180 case 'w': size = 4; break;
2181 case 'h': size = 2; break;
2182 case 'b': size = 1; break;
2183 default: return ERROR_COMMAND_SYNTAX_ERROR;
2186 uint32_t address;
2187 int retval = parse_u32(args[0], &address);
2188 if (ERROR_OK != retval)
2189 return retval;
2191 unsigned count = 1;
2192 if (argc == 2)
2194 retval = parse_uint(args[1], &count);
2195 if (ERROR_OK != retval)
2196 return retval;
2199 uint8_t *buffer = calloc(count, size);
2201 target_t *target = get_current_target(cmd_ctx);
2202 retval = target_read_memory(target,
2203 address, size, count, buffer);
2204 if (ERROR_OK == retval)
2205 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2207 free(buffer);
2209 return retval;
2212 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2214 if ((argc < 2) || (argc > 3))
2215 return ERROR_COMMAND_SYNTAX_ERROR;
2217 uint32_t address;
2218 int retval = parse_u32(args[0], &address);
2219 if (ERROR_OK != retval)
2220 return retval;
2222 uint32_t value;
2223 retval = parse_u32(args[1], &value);
2224 if (ERROR_OK != retval)
2225 return retval;
2227 unsigned count = 1;
2228 if (argc == 3)
2230 retval = parse_uint(args[2], &count);
2231 if (ERROR_OK != retval)
2232 return retval;
2235 target_t *target = get_current_target(cmd_ctx);
2236 unsigned wordsize;
2237 uint8_t value_buf[4];
2238 switch (cmd[2])
2240 case 'w':
2241 wordsize = 4;
2242 target_buffer_set_u32(target, value_buf, value);
2243 break;
2244 case 'h':
2245 wordsize = 2;
2246 target_buffer_set_u16(target, value_buf, value);
2247 break;
2248 case 'b':
2249 wordsize = 1;
2250 value_buf[0] = value;
2251 break;
2252 default:
2253 return ERROR_COMMAND_SYNTAX_ERROR;
2255 for (unsigned i = 0; i < count; i++)
2257 retval = target_write_memory(target,
2258 address + i * wordsize, wordsize, 1, value_buf);
2259 if (ERROR_OK != retval)
2260 return retval;
2261 keep_alive();
2264 return ERROR_OK;
2268 static int parse_load_image_command_args(char **args, int argc,
2269 image_t *image, uint32_t *min_address, uint32_t *max_address)
2271 if (argc < 1 || argc > 5)
2272 return ERROR_COMMAND_SYNTAX_ERROR;
2274 /* a base address isn't always necessary,
2275 * default to 0x0 (i.e. don't relocate) */
2276 if (argc >= 2)
2278 uint32_t addr;
2279 int retval = parse_u32(args[1], &addr);
2280 if (ERROR_OK != retval)
2281 return ERROR_COMMAND_SYNTAX_ERROR;
2282 image->base_address = addr;
2283 image->base_address_set = 1;
2285 else
2286 image->base_address_set = 0;
2288 image->start_address_set = 0;
2290 if (argc >= 4)
2292 int retval = parse_u32(args[3], min_address);
2293 if (ERROR_OK != retval)
2294 return ERROR_COMMAND_SYNTAX_ERROR;
2296 if (argc == 5)
2298 int retval = parse_u32(args[4], max_address);
2299 if (ERROR_OK != retval)
2300 return ERROR_COMMAND_SYNTAX_ERROR;
2301 // use size (given) to find max (required)
2302 *max_address += *min_address;
2305 if (*min_address > *max_address)
2306 return ERROR_COMMAND_SYNTAX_ERROR;
2308 return ERROR_OK;
2311 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2313 uint8_t *buffer;
2314 uint32_t buf_cnt;
2315 uint32_t image_size;
2316 uint32_t min_address = 0;
2317 uint32_t max_address = 0xffffffff;
2318 int i;
2319 int retvaltemp;
2321 image_t image;
2323 duration_t duration;
2324 char *duration_text;
2326 int retval = parse_load_image_command_args(args, argc,
2327 &image, &min_address, &max_address);
2328 if (ERROR_OK != retval)
2329 return retval;
2331 target_t *target = get_current_target(cmd_ctx);
2332 duration_start_measure(&duration);
2334 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2336 return ERROR_OK;
2339 image_size = 0x0;
2340 retval = ERROR_OK;
2341 for (i = 0; i < image.num_sections; i++)
2343 buffer = malloc(image.sections[i].size);
2344 if (buffer == NULL)
2346 command_print(cmd_ctx,
2347 "error allocating buffer for section (%d bytes)",
2348 (int)(image.sections[i].size));
2349 break;
2352 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2354 free(buffer);
2355 break;
2358 uint32_t offset = 0;
2359 uint32_t length = buf_cnt;
2361 /* DANGER!!! beware of unsigned comparision here!!! */
2363 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2364 (image.sections[i].base_address < max_address))
2366 if (image.sections[i].base_address < min_address)
2368 /* clip addresses below */
2369 offset += min_address-image.sections[i].base_address;
2370 length -= offset;
2373 if (image.sections[i].base_address + buf_cnt > max_address)
2375 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2378 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2380 free(buffer);
2381 break;
2383 image_size += length;
2384 command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2385 (unsigned int)length,
2386 image.sections[i].base_address + offset);
2389 free(buffer);
2392 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2394 image_close(&image);
2395 return retvaltemp;
2398 if (retval == ERROR_OK)
2400 command_print(cmd_ctx, "downloaded %u byte in %s",
2401 (unsigned int)image_size,
2402 duration_text);
2404 free(duration_text);
2406 image_close(&image);
2408 return retval;
2412 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2414 fileio_t fileio;
2416 uint8_t buffer[560];
2417 int retvaltemp;
2419 duration_t duration;
2420 char *duration_text;
2422 target_t *target = get_current_target(cmd_ctx);
2424 if (argc != 3)
2426 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2427 return ERROR_OK;
2430 uint32_t address;
2431 int retval = parse_u32(args[1], &address);
2432 if (ERROR_OK != retval)
2433 return retval;
2435 uint32_t size;
2436 retval = parse_u32(args[2], &size);
2437 if (ERROR_OK != retval)
2438 return retval;
2440 if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2442 return ERROR_OK;
2445 duration_start_measure(&duration);
2447 while (size > 0)
2449 uint32_t size_written;
2450 uint32_t this_run_size = (size > 560) ? 560 : size;
2452 retval = target_read_buffer(target, address, this_run_size, buffer);
2453 if (retval != ERROR_OK)
2455 break;
2458 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2459 if (retval != ERROR_OK)
2461 break;
2464 size -= this_run_size;
2465 address += this_run_size;
2468 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2469 return retvaltemp;
2471 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2472 return retvaltemp;
2474 if (retval == ERROR_OK)
2476 command_print(cmd_ctx, "dumped %lld byte in %s",
2477 fileio.size, duration_text);
2478 free(duration_text);
2481 return retval;
2484 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2486 uint8_t *buffer;
2487 uint32_t buf_cnt;
2488 uint32_t image_size;
2489 int i;
2490 int retval, retvaltemp;
2491 uint32_t checksum = 0;
2492 uint32_t mem_checksum = 0;
2494 image_t image;
2496 duration_t duration;
2497 char *duration_text;
2499 target_t *target = get_current_target(cmd_ctx);
2501 if (argc < 1)
2503 return ERROR_COMMAND_SYNTAX_ERROR;
2506 if (!target)
2508 LOG_ERROR("no target selected");
2509 return ERROR_FAIL;
2512 duration_start_measure(&duration);
2514 if (argc >= 2)
2516 uint32_t addr;
2517 retval = parse_u32(args[1], &addr);
2518 if (ERROR_OK != retval)
2519 return ERROR_COMMAND_SYNTAX_ERROR;
2520 image.base_address = addr;
2521 image.base_address_set = 1;
2523 else
2525 image.base_address_set = 0;
2526 image.base_address = 0x0;
2529 image.start_address_set = 0;
2531 if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2533 return retval;
2536 image_size = 0x0;
2537 retval = ERROR_OK;
2538 for (i = 0; i < image.num_sections; i++)
2540 buffer = malloc(image.sections[i].size);
2541 if (buffer == NULL)
2543 command_print(cmd_ctx,
2544 "error allocating buffer for section (%d bytes)",
2545 (int)(image.sections[i].size));
2546 break;
2548 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2550 free(buffer);
2551 break;
2554 if (verify)
2556 /* calculate checksum of image */
2557 image_calculate_checksum(buffer, buf_cnt, &checksum);
2559 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2560 if (retval != ERROR_OK)
2562 free(buffer);
2563 break;
2566 if (checksum != mem_checksum)
2568 /* failed crc checksum, fall back to a binary compare */
2569 uint8_t *data;
2571 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2573 data = (uint8_t*)malloc(buf_cnt);
2575 /* Can we use 32bit word accesses? */
2576 int size = 1;
2577 int count = buf_cnt;
2578 if ((count % 4) == 0)
2580 size *= 4;
2581 count /= 4;
2583 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2584 if (retval == ERROR_OK)
2586 uint32_t t;
2587 for (t = 0; t < buf_cnt; t++)
2589 if (data[t] != buffer[t])
2591 command_print(cmd_ctx,
2592 "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2593 (unsigned)(t + image.sections[i].base_address),
2594 data[t],
2595 buffer[t]);
2596 free(data);
2597 free(buffer);
2598 retval = ERROR_FAIL;
2599 goto done;
2601 if ((t%16384) == 0)
2603 keep_alive();
2608 free(data);
2610 } else
2612 command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2613 image.sections[i].base_address,
2614 buf_cnt);
2617 free(buffer);
2618 image_size += buf_cnt;
2620 done:
2622 if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2624 image_close(&image);
2625 return retvaltemp;
2628 if (retval == ERROR_OK)
2630 command_print(cmd_ctx, "verified %u bytes in %s",
2631 (unsigned int)image_size,
2632 duration_text);
2634 free(duration_text);
2636 image_close(&image);
2638 return retval;
2641 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2643 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2646 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2648 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2651 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2653 target_t *target = get_current_target(cmd_ctx);
2654 breakpoint_t *breakpoint = target->breakpoints;
2655 while (breakpoint)
2657 if (breakpoint->type == BKPT_SOFT)
2659 char* buf = buf_to_str(breakpoint->orig_instr,
2660 breakpoint->length, 16);
2661 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2662 breakpoint->address,
2663 breakpoint->length,
2664 breakpoint->set, buf);
2665 free(buf);
2667 else
2669 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2670 breakpoint->address,
2671 breakpoint->length, breakpoint->set);
2674 breakpoint = breakpoint->next;
2676 return ERROR_OK;
2679 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2680 uint32_t addr, uint32_t length, int hw)
2682 target_t *target = get_current_target(cmd_ctx);
2683 int retval = breakpoint_add(target, addr, length, hw);
2684 if (ERROR_OK == retval)
2685 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2686 else
2687 LOG_ERROR("Failure setting breakpoint");
2688 return retval;
2691 static int handle_bp_command(struct command_context_s *cmd_ctx,
2692 char *cmd, char **args, int argc)
2694 if (argc == 0)
2695 return handle_bp_command_list(cmd_ctx);
2697 if (argc < 2 || argc > 3)
2699 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2700 return ERROR_COMMAND_SYNTAX_ERROR;
2703 uint32_t addr;
2704 int retval = parse_u32(args[0], &addr);
2705 if (ERROR_OK != retval)
2706 return retval;
2708 uint32_t length;
2709 retval = parse_u32(args[1], &length);
2710 if (ERROR_OK != retval)
2711 return retval;
2713 int hw = BKPT_SOFT;
2714 if (argc == 3)
2716 if (strcmp(args[2], "hw") == 0)
2717 hw = BKPT_HARD;
2718 else
2719 return ERROR_COMMAND_SYNTAX_ERROR;
2722 return handle_bp_command_set(cmd_ctx, addr, length, hw);
2725 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2727 if (argc != 1)
2728 return ERROR_COMMAND_SYNTAX_ERROR;
2730 uint32_t addr;
2731 int retval = parse_u32(args[0], &addr);
2732 if (ERROR_OK != retval)
2733 return retval;
2735 target_t *target = get_current_target(cmd_ctx);
2736 breakpoint_remove(target, addr);
2738 return ERROR_OK;
2741 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2743 target_t *target = get_current_target(cmd_ctx);
2745 if (argc == 0)
2747 watchpoint_t *watchpoint = target->watchpoints;
2749 while (watchpoint)
2751 command_print(cmd_ctx,
2752 "address: 0x%8.8" PRIx32 ", len: 0x%8.8x, r/w/a: %i, value: 0x%8.8" PRIx32 ", mask: 0x%8.8" PRIx32 "",
2753 watchpoint->address,
2754 watchpoint->length,
2755 (int)(watchpoint->rw),
2756 watchpoint->value,
2757 watchpoint->mask);
2758 watchpoint = watchpoint->next;
2760 return ERROR_OK;
2763 enum watchpoint_rw type = WPT_ACCESS;
2764 uint32_t addr = 0;
2765 uint32_t length = 0;
2766 uint32_t data_value = 0x0;
2767 uint32_t data_mask = 0xffffffff;
2768 int retval;
2770 switch (argc)
2772 case 5:
2773 retval = parse_u32(args[4], &data_mask);
2774 if (ERROR_OK != retval)
2775 return retval;
2776 // fall through
2777 case 4:
2778 retval = parse_u32(args[3], &data_value);
2779 if (ERROR_OK != retval)
2780 return retval;
2781 // fall through
2782 case 3:
2783 switch (args[2][0])
2785 case 'r':
2786 type = WPT_READ;
2787 break;
2788 case 'w':
2789 type = WPT_WRITE;
2790 break;
2791 case 'a':
2792 type = WPT_ACCESS;
2793 break;
2794 default:
2795 LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2796 return ERROR_COMMAND_SYNTAX_ERROR;
2798 // fall through
2799 case 2:
2800 retval = parse_u32(args[1], &length);
2801 if (ERROR_OK != retval)
2802 return retval;
2803 retval = parse_u32(args[0], &addr);
2804 if (ERROR_OK != retval)
2805 return retval;
2806 break;
2808 default:
2809 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2810 return ERROR_COMMAND_SYNTAX_ERROR;
2813 retval = watchpoint_add(target, addr, length, type,
2814 data_value, data_mask);
2815 if (ERROR_OK != retval)
2816 LOG_ERROR("Failure setting watchpoints");
2818 return retval;
2821 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2823 if (argc != 1)
2824 return ERROR_COMMAND_SYNTAX_ERROR;
2826 uint32_t addr;
2827 int retval = parse_u32(args[0], &addr);
2828 if (ERROR_OK != retval)
2829 return retval;
2831 target_t *target = get_current_target(cmd_ctx);
2832 watchpoint_remove(target, addr);
2834 return ERROR_OK;
2839 * Translate a virtual address to a physical address.
2841 * The low-level target implementation must have logged a detailed error
2842 * which is forwarded to telnet/GDB session.
2844 static int handle_virt2phys_command(command_context_t *cmd_ctx,
2845 char *cmd, char **args, int argc)
2847 if (argc != 1)
2848 return ERROR_COMMAND_SYNTAX_ERROR;
2850 uint32_t va;
2851 int retval = parse_u32(args[0], &va);
2852 if (ERROR_OK != retval)
2853 return retval;
2854 uint32_t pa;
2856 target_t *target = get_current_target(cmd_ctx);
2857 retval = target->type->virt2phys(target, va, &pa);
2858 if (retval == ERROR_OK)
2859 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
2861 return retval;
2864 static void writeData(FILE *f, const void *data, size_t len)
2866 size_t written = fwrite(data, 1, len, f);
2867 if (written != len)
2868 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2871 static void writeLong(FILE *f, int l)
2873 int i;
2874 for (i = 0; i < 4; i++)
2876 char c = (l >> (i*8))&0xff;
2877 writeData(f, &c, 1);
2882 static void writeString(FILE *f, char *s)
2884 writeData(f, s, strlen(s));
2887 /* Dump a gmon.out histogram file. */
2888 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
2890 uint32_t i;
2891 FILE *f = fopen(filename, "w");
2892 if (f == NULL)
2893 return;
2894 writeString(f, "gmon");
2895 writeLong(f, 0x00000001); /* Version */
2896 writeLong(f, 0); /* padding */
2897 writeLong(f, 0); /* padding */
2898 writeLong(f, 0); /* padding */
2900 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2901 writeData(f, &zero, 1);
2903 /* figure out bucket size */
2904 uint32_t min = samples[0];
2905 uint32_t max = samples[0];
2906 for (i = 0; i < sampleNum; i++)
2908 if (min > samples[i])
2910 min = samples[i];
2912 if (max < samples[i])
2914 max = samples[i];
2918 int addressSpace = (max-min + 1);
2920 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2921 uint32_t length = addressSpace;
2922 if (length > maxBuckets)
2924 length = maxBuckets;
2926 int *buckets = malloc(sizeof(int)*length);
2927 if (buckets == NULL)
2929 fclose(f);
2930 return;
2932 memset(buckets, 0, sizeof(int)*length);
2933 for (i = 0; i < sampleNum;i++)
2935 uint32_t address = samples[i];
2936 long long a = address-min;
2937 long long b = length-1;
2938 long long c = addressSpace-1;
2939 int index = (a*b)/c; /* danger!!!! int32 overflows */
2940 buckets[index]++;
2943 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2944 writeLong(f, min); /* low_pc */
2945 writeLong(f, max); /* high_pc */
2946 writeLong(f, length); /* # of samples */
2947 writeLong(f, 64000000); /* 64MHz */
2948 writeString(f, "seconds");
2949 for (i = 0; i < (15-strlen("seconds")); i++)
2950 writeData(f, &zero, 1);
2951 writeString(f, "s");
2953 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2955 char *data = malloc(2*length);
2956 if (data != NULL)
2958 for (i = 0; i < length;i++)
2960 int val;
2961 val = buckets[i];
2962 if (val > 65535)
2964 val = 65535;
2966 data[i*2]=val&0xff;
2967 data[i*2 + 1]=(val >> 8)&0xff;
2969 free(buckets);
2970 writeData(f, data, length * 2);
2971 free(data);
2972 } else
2974 free(buckets);
2977 fclose(f);
2980 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2981 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2983 target_t *target = get_current_target(cmd_ctx);
2984 struct timeval timeout, now;
2986 gettimeofday(&timeout, NULL);
2987 if (argc != 2)
2989 return ERROR_COMMAND_SYNTAX_ERROR;
2991 unsigned offset;
2992 int retval = parse_uint(args[0], &offset);
2993 if (ERROR_OK != retval)
2994 return retval;
2996 timeval_add_time(&timeout, offset, 0);
2998 command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3000 static const int maxSample = 10000;
3001 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3002 if (samples == NULL)
3003 return ERROR_OK;
3005 int numSamples = 0;
3006 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3007 reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
3009 for (;;)
3011 target_poll(target);
3012 if (target->state == TARGET_HALTED)
3014 uint32_t t=*((uint32_t *)reg->value);
3015 samples[numSamples++]=t;
3016 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3017 target_poll(target);
3018 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3019 } else if (target->state == TARGET_RUNNING)
3021 /* We want to quickly sample the PC. */
3022 if ((retval = target_halt(target)) != ERROR_OK)
3024 free(samples);
3025 return retval;
3027 } else
3029 command_print(cmd_ctx, "Target not halted or running");
3030 retval = ERROR_OK;
3031 break;
3033 if (retval != ERROR_OK)
3035 break;
3038 gettimeofday(&now, NULL);
3039 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3041 command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3042 if ((retval = target_poll(target)) != ERROR_OK)
3044 free(samples);
3045 return retval;
3047 if (target->state == TARGET_HALTED)
3049 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3051 if ((retval = target_poll(target)) != ERROR_OK)
3053 free(samples);
3054 return retval;
3056 writeGmon(samples, numSamples, args[1]);
3057 command_print(cmd_ctx, "Wrote %s", args[1]);
3058 break;
3061 free(samples);
3063 return ERROR_OK;
3066 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3068 char *namebuf;
3069 Jim_Obj *nameObjPtr, *valObjPtr;
3070 int result;
3072 namebuf = alloc_printf("%s(%d)", varname, idx);
3073 if (!namebuf)
3074 return JIM_ERR;
3076 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3077 valObjPtr = Jim_NewIntObj(interp, val);
3078 if (!nameObjPtr || !valObjPtr)
3080 free(namebuf);
3081 return JIM_ERR;
3084 Jim_IncrRefCount(nameObjPtr);
3085 Jim_IncrRefCount(valObjPtr);
3086 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3087 Jim_DecrRefCount(interp, nameObjPtr);
3088 Jim_DecrRefCount(interp, valObjPtr);
3089 free(namebuf);
3090 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3091 return result;
3094 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3096 command_context_t *context;
3097 target_t *target;
3099 context = Jim_GetAssocData(interp, "context");
3100 if (context == NULL)
3102 LOG_ERROR("mem2array: no command context");
3103 return JIM_ERR;
3105 target = get_current_target(context);
3106 if (target == NULL)
3108 LOG_ERROR("mem2array: no current target");
3109 return JIM_ERR;
3112 return target_mem2array(interp, target, argc-1, argv + 1);
3115 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3117 long l;
3118 uint32_t width;
3119 int len;
3120 uint32_t addr;
3121 uint32_t count;
3122 uint32_t v;
3123 const char *varname;
3124 uint8_t buffer[4096];
3125 int n, e, retval;
3126 uint32_t i;
3128 /* argv[1] = name of array to receive the data
3129 * argv[2] = desired width
3130 * argv[3] = memory address
3131 * argv[4] = count of times to read
3133 if (argc != 4) {
3134 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3135 return JIM_ERR;
3137 varname = Jim_GetString(argv[0], &len);
3138 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3140 e = Jim_GetLong(interp, argv[1], &l);
3141 width = l;
3142 if (e != JIM_OK) {
3143 return e;
3146 e = Jim_GetLong(interp, argv[2], &l);
3147 addr = l;
3148 if (e != JIM_OK) {
3149 return e;
3151 e = Jim_GetLong(interp, argv[3], &l);
3152 len = l;
3153 if (e != JIM_OK) {
3154 return e;
3156 switch (width) {
3157 case 8:
3158 width = 1;
3159 break;
3160 case 16:
3161 width = 2;
3162 break;
3163 case 32:
3164 width = 4;
3165 break;
3166 default:
3167 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3168 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3169 return JIM_ERR;
3171 if (len == 0) {
3172 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3173 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3174 return JIM_ERR;
3176 if ((addr + (len * width)) < addr) {
3177 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3178 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3179 return JIM_ERR;
3181 /* absurd transfer size? */
3182 if (len > 65536) {
3183 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3184 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3185 return JIM_ERR;
3188 if ((width == 1) ||
3189 ((width == 2) && ((addr & 1) == 0)) ||
3190 ((width == 4) && ((addr & 3) == 0))) {
3191 /* all is well */
3192 } else {
3193 char buf[100];
3194 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3195 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3196 addr,
3197 width);
3198 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3199 return JIM_ERR;
3202 /* Transfer loop */
3204 /* index counter */
3205 n = 0;
3206 /* assume ok */
3207 e = JIM_OK;
3208 while (len) {
3209 /* Slurp... in buffer size chunks */
3211 count = len; /* in objects.. */
3212 if (count > (sizeof(buffer)/width)) {
3213 count = (sizeof(buffer)/width);
3216 retval = target_read_memory(target, addr, width, count, buffer);
3217 if (retval != ERROR_OK) {
3218 /* BOO !*/
3219 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3220 (unsigned int)addr,
3221 (int)width,
3222 (int)count);
3223 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3224 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3225 e = JIM_ERR;
3226 len = 0;
3227 } else {
3228 v = 0; /* shut up gcc */
3229 for (i = 0 ;i < count ;i++, n++) {
3230 switch (width) {
3231 case 4:
3232 v = target_buffer_get_u32(target, &buffer[i*width]);
3233 break;
3234 case 2:
3235 v = target_buffer_get_u16(target, &buffer[i*width]);
3236 break;
3237 case 1:
3238 v = buffer[i] & 0x0ff;
3239 break;
3241 new_int_array_element(interp, varname, n, v);
3243 len -= count;
3247 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3249 return JIM_OK;
3252 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3254 char *namebuf;
3255 Jim_Obj *nameObjPtr, *valObjPtr;
3256 int result;
3257 long l;
3259 namebuf = alloc_printf("%s(%d)", varname, idx);
3260 if (!namebuf)
3261 return JIM_ERR;
3263 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3264 if (!nameObjPtr)
3266 free(namebuf);
3267 return JIM_ERR;
3270 Jim_IncrRefCount(nameObjPtr);
3271 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3272 Jim_DecrRefCount(interp, nameObjPtr);
3273 free(namebuf);
3274 if (valObjPtr == NULL)
3275 return JIM_ERR;
3277 result = Jim_GetLong(interp, valObjPtr, &l);
3278 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3279 *val = l;
3280 return result;
3283 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3285 command_context_t *context;
3286 target_t *target;
3288 context = Jim_GetAssocData(interp, "context");
3289 if (context == NULL) {
3290 LOG_ERROR("array2mem: no command context");
3291 return JIM_ERR;
3293 target = get_current_target(context);
3294 if (target == NULL) {
3295 LOG_ERROR("array2mem: no current target");
3296 return JIM_ERR;
3299 return target_array2mem(interp,target, argc-1, argv + 1);
3302 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3304 long l;
3305 uint32_t width;
3306 int len;
3307 uint32_t addr;
3308 uint32_t count;
3309 uint32_t v;
3310 const char *varname;
3311 uint8_t buffer[4096];
3312 int n, e, retval;
3313 uint32_t i;
3315 /* argv[1] = name of array to get the data
3316 * argv[2] = desired width
3317 * argv[3] = memory address
3318 * argv[4] = count to write
3320 if (argc != 4) {
3321 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3322 return JIM_ERR;
3324 varname = Jim_GetString(argv[0], &len);
3325 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3327 e = Jim_GetLong(interp, argv[1], &l);
3328 width = l;
3329 if (e != JIM_OK) {
3330 return e;
3333 e = Jim_GetLong(interp, argv[2], &l);
3334 addr = l;
3335 if (e != JIM_OK) {
3336 return e;
3338 e = Jim_GetLong(interp, argv[3], &l);
3339 len = l;
3340 if (e != JIM_OK) {
3341 return e;
3343 switch (width) {
3344 case 8:
3345 width = 1;
3346 break;
3347 case 16:
3348 width = 2;
3349 break;
3350 case 32:
3351 width = 4;
3352 break;
3353 default:
3354 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3355 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3356 return JIM_ERR;
3358 if (len == 0) {
3359 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3360 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3361 return JIM_ERR;
3363 if ((addr + (len * width)) < addr) {
3364 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3365 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3366 return JIM_ERR;
3368 /* absurd transfer size? */
3369 if (len > 65536) {
3370 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3371 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3372 return JIM_ERR;
3375 if ((width == 1) ||
3376 ((width == 2) && ((addr & 1) == 0)) ||
3377 ((width == 4) && ((addr & 3) == 0))) {
3378 /* all is well */
3379 } else {
3380 char buf[100];
3381 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3382 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3383 (unsigned int)addr,
3384 (int)width);
3385 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3386 return JIM_ERR;
3389 /* Transfer loop */
3391 /* index counter */
3392 n = 0;
3393 /* assume ok */
3394 e = JIM_OK;
3395 while (len) {
3396 /* Slurp... in buffer size chunks */
3398 count = len; /* in objects.. */
3399 if (count > (sizeof(buffer)/width)) {
3400 count = (sizeof(buffer)/width);
3403 v = 0; /* shut up gcc */
3404 for (i = 0 ;i < count ;i++, n++) {
3405 get_int_array_element(interp, varname, n, &v);
3406 switch (width) {
3407 case 4:
3408 target_buffer_set_u32(target, &buffer[i*width], v);
3409 break;
3410 case 2:
3411 target_buffer_set_u16(target, &buffer[i*width], v);
3412 break;
3413 case 1:
3414 buffer[i] = v & 0x0ff;
3415 break;
3418 len -= count;
3420 retval = target_write_memory(target, addr, width, count, buffer);
3421 if (retval != ERROR_OK) {
3422 /* BOO !*/
3423 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3424 (unsigned int)addr,
3425 (int)width,
3426 (int)count);
3427 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3428 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3429 e = JIM_ERR;
3430 len = 0;
3434 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3436 return JIM_OK;
3439 void target_all_handle_event(enum target_event e)
3441 target_t *target;
3443 LOG_DEBUG("**all*targets: event: %d, %s",
3444 (int)e,
3445 Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3447 target = all_targets;
3448 while (target) {
3449 target_handle_event(target, e);
3450 target = target->next;
3455 /* FIX? should we propagate errors here rather than printing them
3456 * and continuing?
3458 void target_handle_event(target_t *target, enum target_event e)
3460 target_event_action_t *teap;
3462 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3463 if (teap->event == e) {
3464 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3465 target->target_number,
3466 target->cmd_name,
3467 target_get_name(target),
3469 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3470 Jim_GetString(teap->body, NULL));
3471 if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3473 Jim_PrintErrorMessage(interp);
3479 enum target_cfg_param {
3480 TCFG_TYPE,
3481 TCFG_EVENT,
3482 TCFG_WORK_AREA_VIRT,
3483 TCFG_WORK_AREA_PHYS,
3484 TCFG_WORK_AREA_SIZE,
3485 TCFG_WORK_AREA_BACKUP,
3486 TCFG_ENDIAN,
3487 TCFG_VARIANT,
3488 TCFG_CHAIN_POSITION,
3491 static Jim_Nvp nvp_config_opts[] = {
3492 { .name = "-type", .value = TCFG_TYPE },
3493 { .name = "-event", .value = TCFG_EVENT },
3494 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3495 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3496 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3497 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3498 { .name = "-endian" , .value = TCFG_ENDIAN },
3499 { .name = "-variant", .value = TCFG_VARIANT },
3500 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3502 { .name = NULL, .value = -1 }
3505 static int target_configure(Jim_GetOptInfo *goi, target_t *target)
3507 Jim_Nvp *n;
3508 Jim_Obj *o;
3509 jim_wide w;
3510 char *cp;
3511 int e;
3513 /* parse config or cget options ... */
3514 while (goi->argc > 0) {
3515 Jim_SetEmptyResult(goi->interp);
3516 /* Jim_GetOpt_Debug(goi); */
3518 if (target->type->target_jim_configure) {
3519 /* target defines a configure function */
3520 /* target gets first dibs on parameters */
3521 e = (*(target->type->target_jim_configure))(target, goi);
3522 if (e == JIM_OK) {
3523 /* more? */
3524 continue;
3526 if (e == JIM_ERR) {
3527 /* An error */
3528 return e;
3530 /* otherwise we 'continue' below */
3532 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3533 if (e != JIM_OK) {
3534 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3535 return e;
3537 switch (n->value) {
3538 case TCFG_TYPE:
3539 /* not setable */
3540 if (goi->isconfigure) {
3541 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3542 return JIM_ERR;
3543 } else {
3544 no_params:
3545 if (goi->argc != 0) {
3546 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3547 return JIM_ERR;
3550 Jim_SetResultString(goi->interp, target_get_name(target), -1);
3551 /* loop for more */
3552 break;
3553 case TCFG_EVENT:
3554 if (goi->argc == 0) {
3555 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3556 return JIM_ERR;
3559 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3560 if (e != JIM_OK) {
3561 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3562 return e;
3565 if (goi->isconfigure) {
3566 if (goi->argc != 1) {
3567 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3568 return JIM_ERR;
3570 } else {
3571 if (goi->argc != 0) {
3572 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3573 return JIM_ERR;
3578 target_event_action_t *teap;
3580 teap = target->event_action;
3581 /* replace existing? */
3582 while (teap) {
3583 if (teap->event == (enum target_event)n->value) {
3584 break;
3586 teap = teap->next;
3589 if (goi->isconfigure) {
3590 bool replace = true;
3591 if (teap == NULL) {
3592 /* create new */
3593 teap = calloc(1, sizeof(*teap));
3594 replace = false;
3596 teap->event = n->value;
3597 Jim_GetOpt_Obj(goi, &o);
3598 if (teap->body) {
3599 Jim_DecrRefCount(interp, teap->body);
3601 teap->body = Jim_DuplicateObj(goi->interp, o);
3603 * FIXME:
3604 * Tcl/TK - "tk events" have a nice feature.
3605 * See the "BIND" command.
3606 * We should support that here.
3607 * You can specify %X and %Y in the event code.
3608 * The idea is: %T - target name.
3609 * The idea is: %N - target number
3610 * The idea is: %E - event name.
3612 Jim_IncrRefCount(teap->body);
3614 if (!replace)
3616 /* add to head of event list */
3617 teap->next = target->event_action;
3618 target->event_action = teap;
3620 Jim_SetEmptyResult(goi->interp);
3621 } else {
3622 /* get */
3623 if (teap == NULL) {
3624 Jim_SetEmptyResult(goi->interp);
3625 } else {
3626 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3630 /* loop for more */
3631 break;
3633 case TCFG_WORK_AREA_VIRT:
3634 if (goi->isconfigure) {
3635 target_free_all_working_areas(target);
3636 e = Jim_GetOpt_Wide(goi, &w);
3637 if (e != JIM_OK) {
3638 return e;
3640 target->working_area_virt = w;
3641 } else {
3642 if (goi->argc != 0) {
3643 goto no_params;
3646 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3647 /* loop for more */
3648 break;
3650 case TCFG_WORK_AREA_PHYS:
3651 if (goi->isconfigure) {
3652 target_free_all_working_areas(target);
3653 e = Jim_GetOpt_Wide(goi, &w);
3654 if (e != JIM_OK) {
3655 return e;
3657 target->working_area_phys = w;
3658 } else {
3659 if (goi->argc != 0) {
3660 goto no_params;
3663 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3664 /* loop for more */
3665 break;
3667 case TCFG_WORK_AREA_SIZE:
3668 if (goi->isconfigure) {
3669 target_free_all_working_areas(target);
3670 e = Jim_GetOpt_Wide(goi, &w);
3671 if (e != JIM_OK) {
3672 return e;
3674 target->working_area_size = w;
3675 } else {
3676 if (goi->argc != 0) {
3677 goto no_params;
3680 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3681 /* loop for more */
3682 break;
3684 case TCFG_WORK_AREA_BACKUP:
3685 if (goi->isconfigure) {
3686 target_free_all_working_areas(target);
3687 e = Jim_GetOpt_Wide(goi, &w);
3688 if (e != JIM_OK) {
3689 return e;
3691 /* make this exactly 1 or 0 */
3692 target->backup_working_area = (!!w);
3693 } else {
3694 if (goi->argc != 0) {
3695 goto no_params;
3698 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3699 /* loop for more e*/
3700 break;
3702 case TCFG_ENDIAN:
3703 if (goi->isconfigure) {
3704 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3705 if (e != JIM_OK) {
3706 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3707 return e;
3709 target->endianness = n->value;
3710 } else {
3711 if (goi->argc != 0) {
3712 goto no_params;
3715 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3716 if (n->name == NULL) {
3717 target->endianness = TARGET_LITTLE_ENDIAN;
3718 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3720 Jim_SetResultString(goi->interp, n->name, -1);
3721 /* loop for more */
3722 break;
3724 case TCFG_VARIANT:
3725 if (goi->isconfigure) {
3726 if (goi->argc < 1) {
3727 Jim_SetResult_sprintf(goi->interp,
3728 "%s ?STRING?",
3729 n->name);
3730 return JIM_ERR;
3732 if (target->variant) {
3733 free((void *)(target->variant));
3735 e = Jim_GetOpt_String(goi, &cp, NULL);
3736 target->variant = strdup(cp);
3737 } else {
3738 if (goi->argc != 0) {
3739 goto no_params;
3742 Jim_SetResultString(goi->interp, target->variant,-1);
3743 /* loop for more */
3744 break;
3745 case TCFG_CHAIN_POSITION:
3746 if (goi->isconfigure) {
3747 Jim_Obj *o;
3748 jtag_tap_t *tap;
3749 target_free_all_working_areas(target);
3750 e = Jim_GetOpt_Obj(goi, &o);
3751 if (e != JIM_OK) {
3752 return e;
3754 tap = jtag_tap_by_jim_obj(goi->interp, o);
3755 if (tap == NULL) {
3756 return JIM_ERR;
3758 /* make this exactly 1 or 0 */
3759 target->tap = tap;
3760 } else {
3761 if (goi->argc != 0) {
3762 goto no_params;
3765 Jim_SetResultString(interp, target->tap->dotted_name, -1);
3766 /* loop for more e*/
3767 break;
3769 } /* while (goi->argc) */
3772 /* done - we return */
3773 return JIM_OK;
3776 /** this is the 'tcl' handler for the target specific command */
3777 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3779 Jim_GetOptInfo goi;
3780 jim_wide a,b,c;
3781 int x,y,z;
3782 uint8_t target_buf[32];
3783 Jim_Nvp *n;
3784 target_t *target;
3785 struct command_context_s *cmd_ctx;
3786 int e;
3788 enum {
3789 TS_CMD_CONFIGURE,
3790 TS_CMD_CGET,
3792 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3793 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3794 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3795 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3796 TS_CMD_EXAMINE,
3797 TS_CMD_POLL,
3798 TS_CMD_RESET,
3799 TS_CMD_HALT,
3800 TS_CMD_WAITSTATE,
3801 TS_CMD_EVENTLIST,
3802 TS_CMD_CURSTATE,
3803 TS_CMD_INVOKE_EVENT,
3806 static const Jim_Nvp target_options[] = {
3807 { .name = "configure", .value = TS_CMD_CONFIGURE },
3808 { .name = "cget", .value = TS_CMD_CGET },
3809 { .name = "mww", .value = TS_CMD_MWW },
3810 { .name = "mwh", .value = TS_CMD_MWH },
3811 { .name = "mwb", .value = TS_CMD_MWB },
3812 { .name = "mdw", .value = TS_CMD_MDW },
3813 { .name = "mdh", .value = TS_CMD_MDH },
3814 { .name = "mdb", .value = TS_CMD_MDB },
3815 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3816 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3817 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3818 { .name = "curstate", .value = TS_CMD_CURSTATE },
3820 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3821 { .name = "arp_poll", .value = TS_CMD_POLL },
3822 { .name = "arp_reset", .value = TS_CMD_RESET },
3823 { .name = "arp_halt", .value = TS_CMD_HALT },
3824 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3825 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3827 { .name = NULL, .value = -1 },
3830 /* go past the "command" */
3831 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3833 target = Jim_CmdPrivData(goi.interp);
3834 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3836 /* commands here are in an NVP table */
3837 e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3838 if (e != JIM_OK) {
3839 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3840 return e;
3842 /* Assume blank result */
3843 Jim_SetEmptyResult(goi.interp);
3845 switch (n->value) {
3846 case TS_CMD_CONFIGURE:
3847 if (goi.argc < 2) {
3848 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3849 return JIM_ERR;
3851 goi.isconfigure = 1;
3852 return target_configure(&goi, target);
3853 case TS_CMD_CGET:
3854 // some things take params
3855 if (goi.argc < 1) {
3856 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3857 return JIM_ERR;
3859 goi.isconfigure = 0;
3860 return target_configure(&goi, target);
3861 break;
3862 case TS_CMD_MWW:
3863 case TS_CMD_MWH:
3864 case TS_CMD_MWB:
3865 /* argv[0] = cmd
3866 * argv[1] = address
3867 * argv[2] = data
3868 * argv[3] = optional count.
3871 if ((goi.argc == 2) || (goi.argc == 3)) {
3872 /* all is well */
3873 } else {
3874 mwx_error:
3875 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
3876 return JIM_ERR;
3879 e = Jim_GetOpt_Wide(&goi, &a);
3880 if (e != JIM_OK) {
3881 goto mwx_error;
3884 e = Jim_GetOpt_Wide(&goi, &b);
3885 if (e != JIM_OK) {
3886 goto mwx_error;
3888 if (goi.argc == 3) {
3889 e = Jim_GetOpt_Wide(&goi, &c);
3890 if (e != JIM_OK) {
3891 goto mwx_error;
3893 } else {
3894 c = 1;
3897 switch (n->value) {
3898 case TS_CMD_MWW:
3899 target_buffer_set_u32(target, target_buf, b);
3900 b = 4;
3901 break;
3902 case TS_CMD_MWH:
3903 target_buffer_set_u16(target, target_buf, b);
3904 b = 2;
3905 break;
3906 case TS_CMD_MWB:
3907 target_buffer_set_u8(target, target_buf, b);
3908 b = 1;
3909 break;
3911 for (x = 0 ; x < c ; x++) {
3912 e = target_write_memory(target, a, b, 1, target_buf);
3913 if (e != ERROR_OK) {
3914 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
3915 return JIM_ERR;
3917 /* b = width */
3918 a = a + b;
3920 return JIM_OK;
3921 break;
3923 /* display */
3924 case TS_CMD_MDW:
3925 case TS_CMD_MDH:
3926 case TS_CMD_MDB:
3927 /* argv[0] = command
3928 * argv[1] = address
3929 * argv[2] = optional count
3931 if ((goi.argc == 2) || (goi.argc == 3)) {
3932 Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
3933 return JIM_ERR;
3935 e = Jim_GetOpt_Wide(&goi, &a);
3936 if (e != JIM_OK) {
3937 return JIM_ERR;
3939 if (goi.argc) {
3940 e = Jim_GetOpt_Wide(&goi, &c);
3941 if (e != JIM_OK) {
3942 return JIM_ERR;
3944 } else {
3945 c = 1;
3947 b = 1; /* shut up gcc */
3948 switch (n->value) {
3949 case TS_CMD_MDW:
3950 b = 4;
3951 break;
3952 case TS_CMD_MDH:
3953 b = 2;
3954 break;
3955 case TS_CMD_MDB:
3956 b = 1;
3957 break;
3960 /* convert to "bytes" */
3961 c = c * b;
3962 /* count is now in 'BYTES' */
3963 while (c > 0) {
3964 y = c;
3965 if (y > 16) {
3966 y = 16;
3968 e = target_read_memory(target, a, b, y / b, target_buf);
3969 if (e != ERROR_OK) {
3970 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
3971 return JIM_ERR;
3974 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
3975 switch (b) {
3976 case 4:
3977 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
3978 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
3979 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
3981 for (; (x < 16) ; x += 4) {
3982 Jim_fprintf(interp, interp->cookie_stdout, " ");
3984 break;
3985 case 2:
3986 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
3987 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
3988 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
3990 for (; (x < 16) ; x += 2) {
3991 Jim_fprintf(interp, interp->cookie_stdout, " ");
3993 break;
3994 case 1:
3995 default:
3996 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
3997 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
3998 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4000 for (; (x < 16) ; x += 1) {
4001 Jim_fprintf(interp, interp->cookie_stdout, " ");
4003 break;
4005 /* ascii-ify the bytes */
4006 for (x = 0 ; x < y ; x++) {
4007 if ((target_buf[x] >= 0x20) &&
4008 (target_buf[x] <= 0x7e)) {
4009 /* good */
4010 } else {
4011 /* smack it */
4012 target_buf[x] = '.';
4015 /* space pad */
4016 while (x < 16) {
4017 target_buf[x] = ' ';
4018 x++;
4020 /* terminate */
4021 target_buf[16] = 0;
4022 /* print - with a newline */
4023 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4024 /* NEXT... */
4025 c -= 16;
4026 a += 16;
4028 return JIM_OK;
4029 case TS_CMD_MEM2ARRAY:
4030 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4031 break;
4032 case TS_CMD_ARRAY2MEM:
4033 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4034 break;
4035 case TS_CMD_EXAMINE:
4036 if (goi.argc) {
4037 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4038 return JIM_ERR;
4040 if (!target->tap->enabled)
4041 goto err_tap_disabled;
4042 e = target->type->examine(target);
4043 if (e != ERROR_OK) {
4044 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4045 return JIM_ERR;
4047 return JIM_OK;
4048 case TS_CMD_POLL:
4049 if (goi.argc) {
4050 Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4051 return JIM_ERR;
4053 if (!target->tap->enabled)
4054 goto err_tap_disabled;
4055 if (!(target_was_examined(target))) {
4056 e = ERROR_TARGET_NOT_EXAMINED;
4057 } else {
4058 e = target->type->poll(target);
4060 if (e != ERROR_OK) {
4061 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4062 return JIM_ERR;
4063 } else {
4064 return JIM_OK;
4066 break;
4067 case TS_CMD_RESET:
4068 if (goi.argc != 2) {
4069 Jim_WrongNumArgs(interp, 2, argv,
4070 "([tT]|[fF]|assert|deassert) BOOL");
4071 return JIM_ERR;
4073 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4074 if (e != JIM_OK) {
4075 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4076 return e;
4078 /* the halt or not param */
4079 e = Jim_GetOpt_Wide(&goi, &a);
4080 if (e != JIM_OK) {
4081 return e;
4083 if (!target->tap->enabled)
4084 goto err_tap_disabled;
4085 if (!target->type->assert_reset
4086 || !target->type->deassert_reset) {
4087 Jim_SetResult_sprintf(interp,
4088 "No target-specific reset for %s",
4089 target->cmd_name);
4090 return JIM_ERR;
4092 /* determine if we should halt or not. */
4093 target->reset_halt = !!a;
4094 /* When this happens - all workareas are invalid. */
4095 target_free_all_working_areas_restore(target, 0);
4097 /* do the assert */
4098 if (n->value == NVP_ASSERT) {
4099 e = target->type->assert_reset(target);
4100 } else {
4101 e = target->type->deassert_reset(target);
4103 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4104 case TS_CMD_HALT:
4105 if (goi.argc) {
4106 Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4107 return JIM_ERR;
4109 if (!target->tap->enabled)
4110 goto err_tap_disabled;
4111 e = target->type->halt(target);
4112 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4113 case TS_CMD_WAITSTATE:
4114 /* params: <name> statename timeoutmsecs */
4115 if (goi.argc != 2) {
4116 Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4117 return JIM_ERR;
4119 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4120 if (e != JIM_OK) {
4121 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4122 return e;
4124 e = Jim_GetOpt_Wide(&goi, &a);
4125 if (e != JIM_OK) {
4126 return e;
4128 if (!target->tap->enabled)
4129 goto err_tap_disabled;
4130 e = target_wait_state(target, n->value, a);
4131 if (e != ERROR_OK) {
4132 Jim_SetResult_sprintf(goi.interp,
4133 "target: %s wait %s fails (%d) %s",
4134 target->cmd_name,
4135 n->name,
4136 e, target_strerror_safe(e));
4137 return JIM_ERR;
4138 } else {
4139 return JIM_OK;
4141 case TS_CMD_EVENTLIST:
4142 /* List for human, Events defined for this target.
4143 * scripts/programs should use 'name cget -event NAME'
4146 target_event_action_t *teap;
4147 teap = target->event_action;
4148 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4149 target->target_number,
4150 target->cmd_name);
4151 command_print(cmd_ctx, "%-25s | Body", "Event");
4152 command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4153 while (teap) {
4154 command_print(cmd_ctx,
4155 "%-25s | %s",
4156 Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4157 Jim_GetString(teap->body, NULL));
4158 teap = teap->next;
4160 command_print(cmd_ctx, "***END***");
4161 return JIM_OK;
4163 case TS_CMD_CURSTATE:
4164 if (goi.argc != 0) {
4165 Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4166 return JIM_ERR;
4168 Jim_SetResultString(goi.interp,
4169 target_state_name( target ),
4170 -1);
4171 return JIM_OK;
4172 case TS_CMD_INVOKE_EVENT:
4173 if (goi.argc != 1) {
4174 Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4175 return JIM_ERR;
4177 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4178 if (e != JIM_OK) {
4179 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4180 return e;
4182 target_handle_event(target, n->value);
4183 return JIM_OK;
4185 return JIM_ERR;
4187 err_tap_disabled:
4188 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4189 return JIM_ERR;
4192 static int target_create(Jim_GetOptInfo *goi)
4194 Jim_Obj *new_cmd;
4195 Jim_Cmd *cmd;
4196 const char *cp;
4197 char *cp2;
4198 int e;
4199 int x;
4200 target_t *target;
4201 struct command_context_s *cmd_ctx;
4203 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4204 if (goi->argc < 3) {
4205 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4206 return JIM_ERR;
4209 /* COMMAND */
4210 Jim_GetOpt_Obj(goi, &new_cmd);
4211 /* does this command exist? */
4212 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4213 if (cmd) {
4214 cp = Jim_GetString(new_cmd, NULL);
4215 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4216 return JIM_ERR;
4219 /* TYPE */
4220 e = Jim_GetOpt_String(goi, &cp2, NULL);
4221 cp = cp2;
4222 /* now does target type exist */
4223 for (x = 0 ; target_types[x] ; x++) {
4224 if (0 == strcmp(cp, target_types[x]->name)) {
4225 /* found */
4226 break;
4229 if (target_types[x] == NULL) {
4230 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4231 for (x = 0 ; target_types[x] ; x++) {
4232 if (target_types[x + 1]) {
4233 Jim_AppendStrings(goi->interp,
4234 Jim_GetResult(goi->interp),
4235 target_types[x]->name,
4236 ", ", NULL);
4237 } else {
4238 Jim_AppendStrings(goi->interp,
4239 Jim_GetResult(goi->interp),
4240 " or ",
4241 target_types[x]->name,NULL);
4244 return JIM_ERR;
4247 /* Create it */
4248 target = calloc(1,sizeof(target_t));
4249 /* set target number */
4250 target->target_number = new_target_number();
4252 /* allocate memory for each unique target type */
4253 target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4255 memcpy(target->type, target_types[x], sizeof(target_type_t));
4257 /* will be set by "-endian" */
4258 target->endianness = TARGET_ENDIAN_UNKNOWN;
4260 target->working_area = 0x0;
4261 target->working_area_size = 0x0;
4262 target->working_areas = NULL;
4263 target->backup_working_area = 0;
4265 target->state = TARGET_UNKNOWN;
4266 target->debug_reason = DBG_REASON_UNDEFINED;
4267 target->reg_cache = NULL;
4268 target->breakpoints = NULL;
4269 target->watchpoints = NULL;
4270 target->next = NULL;
4271 target->arch_info = NULL;
4273 target->display = 1;
4275 target->halt_issued = false;
4277 /* initialize trace information */
4278 target->trace_info = malloc(sizeof(trace_t));
4279 target->trace_info->num_trace_points = 0;
4280 target->trace_info->trace_points_size = 0;
4281 target->trace_info->trace_points = NULL;
4282 target->trace_info->trace_history_size = 0;
4283 target->trace_info->trace_history = NULL;
4284 target->trace_info->trace_history_pos = 0;
4285 target->trace_info->trace_history_overflowed = 0;
4287 target->dbgmsg = NULL;
4288 target->dbg_msg_enabled = 0;
4290 target->endianness = TARGET_ENDIAN_UNKNOWN;
4292 /* Do the rest as "configure" options */
4293 goi->isconfigure = 1;
4294 e = target_configure(goi, target);
4296 if (target->tap == NULL)
4298 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4299 e = JIM_ERR;
4302 if (e != JIM_OK) {
4303 free(target->type);
4304 free(target);
4305 return e;
4308 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4309 /* default endian to little if not specified */
4310 target->endianness = TARGET_LITTLE_ENDIAN;
4313 /* incase variant is not set */
4314 if (!target->variant)
4315 target->variant = strdup("");
4317 /* create the target specific commands */
4318 if (target->type->register_commands) {
4319 (*(target->type->register_commands))(cmd_ctx);
4321 if (target->type->target_create) {
4322 (*(target->type->target_create))(target, goi->interp);
4325 /* append to end of list */
4327 target_t **tpp;
4328 tpp = &(all_targets);
4329 while (*tpp) {
4330 tpp = &((*tpp)->next);
4332 *tpp = target;
4335 cp = Jim_GetString(new_cmd, NULL);
4336 target->cmd_name = strdup(cp);
4338 /* now - create the new target name command */
4339 e = Jim_CreateCommand(goi->interp,
4340 /* name */
4342 tcl_target_func, /* C function */
4343 target, /* private data */
4344 NULL); /* no del proc */
4346 return e;
4349 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4351 int x,r,e;
4352 jim_wide w;
4353 struct command_context_s *cmd_ctx;
4354 target_t *target;
4355 Jim_GetOptInfo goi;
4356 enum tcmd {
4357 /* TG = target generic */
4358 TG_CMD_CREATE,
4359 TG_CMD_TYPES,
4360 TG_CMD_NAMES,
4361 TG_CMD_CURRENT,
4362 TG_CMD_NUMBER,
4363 TG_CMD_COUNT,
4365 const char *target_cmds[] = {
4366 "create", "types", "names", "current", "number",
4367 "count",
4368 NULL /* terminate */
4371 LOG_DEBUG("Target command params:");
4372 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4374 cmd_ctx = Jim_GetAssocData(interp, "context");
4376 Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4378 if (goi.argc == 0) {
4379 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4380 return JIM_ERR;
4383 /* Jim_GetOpt_Debug(&goi); */
4384 r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4385 if (r != JIM_OK) {
4386 return r;
4389 switch (x) {
4390 default:
4391 Jim_Panic(goi.interp,"Why am I here?");
4392 return JIM_ERR;
4393 case TG_CMD_CURRENT:
4394 if (goi.argc != 0) {
4395 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4396 return JIM_ERR;
4398 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4399 return JIM_OK;
4400 case TG_CMD_TYPES:
4401 if (goi.argc != 0) {
4402 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4403 return JIM_ERR;
4405 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4406 for (x = 0 ; target_types[x] ; x++) {
4407 Jim_ListAppendElement(goi.interp,
4408 Jim_GetResult(goi.interp),
4409 Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4411 return JIM_OK;
4412 case TG_CMD_NAMES:
4413 if (goi.argc != 0) {
4414 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4415 return JIM_ERR;
4417 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4418 target = all_targets;
4419 while (target) {
4420 Jim_ListAppendElement(goi.interp,
4421 Jim_GetResult(goi.interp),
4422 Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4423 target = target->next;
4425 return JIM_OK;
4426 case TG_CMD_CREATE:
4427 if (goi.argc < 3) {
4428 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4429 return JIM_ERR;
4431 return target_create(&goi);
4432 break;
4433 case TG_CMD_NUMBER:
4434 /* It's OK to remove this mechanism sometime after August 2010 or so */
4435 LOG_WARNING("don't use numbers as target identifiers; use names");
4436 if (goi.argc != 1) {
4437 Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4438 return JIM_ERR;
4440 e = Jim_GetOpt_Wide(&goi, &w);
4441 if (e != JIM_OK) {
4442 return JIM_ERR;
4444 for (x = 0, target = all_targets; target; target = target->next, x++) {
4445 if (target->target_number == w)
4446 break;
4448 if (target == NULL) {
4449 Jim_SetResult_sprintf(goi.interp,
4450 "Target: number %d does not exist", (int)(w));
4451 return JIM_ERR;
4453 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4454 return JIM_OK;
4455 case TG_CMD_COUNT:
4456 if (goi.argc != 0) {
4457 Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4458 return JIM_ERR;
4460 for (x = 0, target = all_targets; target; target = target->next, x++)
4461 continue;
4462 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4463 return JIM_OK;
4466 return JIM_ERR;
4470 struct FastLoad
4472 uint32_t address;
4473 uint8_t *data;
4474 int length;
4478 static int fastload_num;
4479 static struct FastLoad *fastload;
4481 static void free_fastload(void)
4483 if (fastload != NULL)
4485 int i;
4486 for (i = 0; i < fastload_num; i++)
4488 if (fastload[i].data)
4489 free(fastload[i].data);
4491 free(fastload);
4492 fastload = NULL;
4499 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4501 uint8_t *buffer;
4502 uint32_t buf_cnt;
4503 uint32_t image_size;
4504 uint32_t min_address = 0;
4505 uint32_t max_address = 0xffffffff;
4506 int i;
4508 image_t image;
4510 duration_t duration;
4511 char *duration_text;
4513 int retval = parse_load_image_command_args(args, argc,
4514 &image, &min_address, &max_address);
4515 if (ERROR_OK != retval)
4516 return retval;
4518 duration_start_measure(&duration);
4520 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4522 return ERROR_OK;
4525 image_size = 0x0;
4526 retval = ERROR_OK;
4527 fastload_num = image.num_sections;
4528 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4529 if (fastload == NULL)
4531 image_close(&image);
4532 return ERROR_FAIL;
4534 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4535 for (i = 0; i < image.num_sections; i++)
4537 buffer = malloc(image.sections[i].size);
4538 if (buffer == NULL)
4540 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4541 (int)(image.sections[i].size));
4542 break;
4545 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4547 free(buffer);
4548 break;
4551 uint32_t offset = 0;
4552 uint32_t length = buf_cnt;
4555 /* DANGER!!! beware of unsigned comparision here!!! */
4557 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4558 (image.sections[i].base_address < max_address))
4560 if (image.sections[i].base_address < min_address)
4562 /* clip addresses below */
4563 offset += min_address-image.sections[i].base_address;
4564 length -= offset;
4567 if (image.sections[i].base_address + buf_cnt > max_address)
4569 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4572 fastload[i].address = image.sections[i].base_address + offset;
4573 fastload[i].data = malloc(length);
4574 if (fastload[i].data == NULL)
4576 free(buffer);
4577 break;
4579 memcpy(fastload[i].data, buffer + offset, length);
4580 fastload[i].length = length;
4582 image_size += length;
4583 command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4584 (unsigned int)length,
4585 ((unsigned int)(image.sections[i].base_address + offset)));
4588 free(buffer);
4591 duration_stop_measure(&duration, &duration_text);
4592 if (retval == ERROR_OK)
4594 command_print(cmd_ctx, "Loaded %u bytes in %s", (unsigned int)image_size, duration_text);
4595 command_print(cmd_ctx, "NB!!! image has not been loaded to target, issue a subsequent 'fast_load' to do so.");
4597 free(duration_text);
4599 image_close(&image);
4601 if (retval != ERROR_OK)
4603 free_fastload();
4606 return retval;
4609 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4611 if (argc > 0)
4612 return ERROR_COMMAND_SYNTAX_ERROR;
4613 if (fastload == NULL)
4615 LOG_ERROR("No image in memory");
4616 return ERROR_FAIL;
4618 int i;
4619 int ms = timeval_ms();
4620 int size = 0;
4621 int retval = ERROR_OK;
4622 for (i = 0; i < fastload_num;i++)
4624 target_t *target = get_current_target(cmd_ctx);
4625 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4626 (unsigned int)(fastload[i].address),
4627 (unsigned int)(fastload[i].length));
4628 if (retval == ERROR_OK)
4630 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4632 size += fastload[i].length;
4634 int after = timeval_ms();
4635 command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4636 return retval;
4641 * Local Variables:
4642 * c-basic-offset: 4
4643 * tab-width: 4
4644 * End: