less warnings
[openocd.git] / src / target / target.c
blob3dee1891967d2c560c1fe587699fead5c72a8720
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007,2008 Ø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 feroceon_target;
86 extern target_type_t xscale_target;
87 extern target_type_t cortexm3_target;
88 extern target_type_t cortexa8_target;
89 extern target_type_t arm11_target;
90 extern target_type_t mips_m4k_target;
91 extern target_type_t avr_target;
93 target_type_t *target_types[] =
95 &arm7tdmi_target,
96 &arm9tdmi_target,
97 &arm920t_target,
98 &arm720t_target,
99 &arm966e_target,
100 &arm926ejs_target,
101 &feroceon_target,
102 &xscale_target,
103 &cortexm3_target,
104 &cortexa8_target,
105 &arm11_target,
106 &mips_m4k_target,
107 &avr_target,
108 NULL,
111 target_t *all_targets = NULL;
112 target_event_callback_t *target_event_callbacks = NULL;
113 target_timer_callback_t *target_timer_callbacks = NULL;
115 const Jim_Nvp nvp_assert[] = {
116 { .name = "assert", NVP_ASSERT },
117 { .name = "deassert", NVP_DEASSERT },
118 { .name = "T", NVP_ASSERT },
119 { .name = "F", NVP_DEASSERT },
120 { .name = "t", NVP_ASSERT },
121 { .name = "f", NVP_DEASSERT },
122 { .name = NULL, .value = -1 }
125 const Jim_Nvp nvp_error_target[] = {
126 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
127 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
128 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
129 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
130 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
131 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
132 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
133 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
134 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
135 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
136 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
137 { .value = -1, .name = NULL }
140 const char *target_strerror_safe( int err )
142 const Jim_Nvp *n;
144 n = Jim_Nvp_value2name_simple( nvp_error_target, err );
145 if( n->name == NULL ){
146 return "unknown";
147 } else {
148 return n->name;
152 static const Jim_Nvp nvp_target_event[] = {
153 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
154 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
156 { .value = TARGET_EVENT_EARLY_HALTED, .name = "early-halted" },
157 { .value = TARGET_EVENT_HALTED, .name = "halted" },
158 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
159 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
160 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
162 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
163 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
165 /* historical name */
167 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
169 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
170 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
171 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
172 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
173 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
174 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
175 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
176 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
177 { .value = TARGET_EVENT_RESET_INIT , .name = "reset-init" },
178 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
180 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
181 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
183 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
184 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
186 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
187 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
189 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
190 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
192 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
193 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
195 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
196 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
197 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
199 { .name = NULL, .value = -1 }
202 const Jim_Nvp nvp_target_state[] = {
203 { .name = "unknown", .value = TARGET_UNKNOWN },
204 { .name = "running", .value = TARGET_RUNNING },
205 { .name = "halted", .value = TARGET_HALTED },
206 { .name = "reset", .value = TARGET_RESET },
207 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
208 { .name = NULL, .value = -1 },
211 const Jim_Nvp nvp_target_debug_reason [] = {
212 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
213 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
214 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
215 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
216 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
217 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
218 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
219 { .name = NULL, .value = -1 },
222 const Jim_Nvp nvp_target_endian[] = {
223 { .name = "big", .value = TARGET_BIG_ENDIAN },
224 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
225 { .name = "be", .value = TARGET_BIG_ENDIAN },
226 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
227 { .name = NULL, .value = -1 },
230 const Jim_Nvp nvp_reset_modes[] = {
231 { .name = "unknown", .value = RESET_UNKNOWN },
232 { .name = "run" , .value = RESET_RUN },
233 { .name = "halt" , .value = RESET_HALT },
234 { .name = "init" , .value = RESET_INIT },
235 { .name = NULL , .value = -1 },
238 static int max_target_number(void)
240 target_t *t;
241 int x;
243 x = -1;
244 t = all_targets;
245 while( t ){
246 if( x < t->target_number ){
247 x = (t->target_number)+1;
249 t = t->next;
251 return x;
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 static int target_continuous_poll = 1;
274 /* read a uint32_t from a buffer in target memory endianness */
275 uint32_t target_buffer_get_u32(target_t *target, const uint8_t *buffer)
277 if (target->endianness == TARGET_LITTLE_ENDIAN)
278 return le_to_h_u32(buffer);
279 else
280 return be_to_h_u32(buffer);
283 /* read a uint16_t from a buffer in target memory endianness */
284 uint16_t target_buffer_get_u16(target_t *target, const uint8_t *buffer)
286 if (target->endianness == TARGET_LITTLE_ENDIAN)
287 return le_to_h_u16(buffer);
288 else
289 return be_to_h_u16(buffer);
292 /* read a uint8_t from a buffer in target memory endianness */
293 uint8_t target_buffer_get_u8(target_t *target, const uint8_t *buffer)
295 return *buffer & 0x0ff;
298 /* write a uint32_t to a buffer in target memory endianness */
299 void target_buffer_set_u32(target_t *target, uint8_t *buffer, uint32_t value)
301 if (target->endianness == TARGET_LITTLE_ENDIAN)
302 h_u32_to_le(buffer, value);
303 else
304 h_u32_to_be(buffer, value);
307 /* write a uint16_t to a buffer in target memory endianness */
308 void target_buffer_set_u16(target_t *target, uint8_t *buffer, uint16_t value)
310 if (target->endianness == TARGET_LITTLE_ENDIAN)
311 h_u16_to_le(buffer, value);
312 else
313 h_u16_to_be(buffer, value);
316 /* write a uint8_t to a buffer in target memory endianness */
317 void target_buffer_set_u8(target_t *target, uint8_t *buffer, uint8_t value)
319 *buffer = value;
322 /* return a pointer to a configured target; id is name or number */
323 target_t *get_target(const char *id)
325 target_t *target;
327 /* try as tcltarget name */
328 for (target = all_targets; target; target = target->next) {
329 if (target->cmd_name == NULL)
330 continue;
331 if (strcmp(id, target->cmd_name) == 0)
332 return target;
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 return target;
345 return NULL;
348 /* returns a pointer to the n-th configured target */
349 static target_t *get_target_by_num(int num)
351 target_t *target = all_targets;
353 while (target){
354 if( target->target_number == num ){
355 return target;
357 target = target->next;
360 return NULL;
363 int get_num_by_target(target_t *query_target)
365 return query_target->target_number;
368 target_t* get_current_target(command_context_t *cmd_ctx)
370 target_t *target = get_target_by_num(cmd_ctx->current_target);
372 if (target == NULL)
374 LOG_ERROR("BUG: current_target out of bounds");
375 exit(-1);
378 return target;
381 int target_poll(struct target_s *target)
383 /* We can't poll until after examine */
384 if (!target_was_examined(target))
386 /* Fail silently lest we pollute the log */
387 return ERROR_FAIL;
389 return target->type->poll(target);
392 int target_halt(struct target_s *target)
394 /* We can't poll until after examine */
395 if (!target_was_examined(target))
397 LOG_ERROR("Target not examined yet");
398 return ERROR_FAIL;
400 return target->type->halt(target);
403 int target_resume(struct target_s *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
405 int retval;
407 /* We can't poll until after examine */
408 if (!target_was_examined(target))
410 LOG_ERROR("Target not examined yet");
411 return ERROR_FAIL;
414 /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
415 * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
416 * the application.
418 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
419 return retval;
421 return retval;
424 int target_process_reset(struct command_context_s *cmd_ctx, enum target_reset_mode reset_mode)
426 char buf[100];
427 int retval;
428 Jim_Nvp *n;
429 n = Jim_Nvp_value2name_simple( nvp_reset_modes, reset_mode );
430 if( n->name == NULL ){
431 LOG_ERROR("invalid reset mode");
432 return ERROR_FAIL;
435 /* disable polling during reset to make reset event scripts
436 * more predictable, i.e. dr/irscan & pathmove in events will
437 * not have JTAG operations injected into the middle of a sequence.
439 int save_poll = target_continuous_poll;
440 target_continuous_poll = 0;
442 sprintf( buf, "ocd_process_reset %s", n->name );
443 retval = Jim_Eval( interp, buf );
445 target_continuous_poll = save_poll;
447 if(retval != JIM_OK) {
448 Jim_PrintErrorMessage(interp);
449 return ERROR_FAIL;
452 /* We want any events to be processed before the prompt */
453 retval = target_call_timer_callbacks_now();
455 return retval;
458 static int default_virt2phys(struct target_s *target, uint32_t virtual, uint32_t *physical)
460 *physical = virtual;
461 return ERROR_OK;
464 static int default_mmu(struct target_s *target, int *enabled)
466 *enabled = 0;
467 return ERROR_OK;
470 static int default_examine(struct target_s *target)
472 target_set_examined(target);
473 return ERROR_OK;
476 int target_examine_one(struct target_s *target)
478 return target->type->examine(target);
481 static int jtag_enable_callback(enum jtag_event event, void *priv)
483 target_t *target = priv;
485 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
486 return ERROR_OK;
488 jtag_unregister_event_callback(jtag_enable_callback, target);
489 return target_examine_one(target);
493 /* Targets that correctly implement init+examine, i.e.
494 * no communication with target during init:
496 * XScale
498 int target_examine(void)
500 int retval = ERROR_OK;
501 target_t *target;
503 for (target = all_targets; target; target = target->next)
505 /* defer examination, but don't skip it */
506 if (!target->tap->enabled) {
507 jtag_register_event_callback(jtag_enable_callback,
508 target);
509 continue;
511 if ((retval = target_examine_one(target)) != ERROR_OK)
512 return retval;
514 return retval;
516 const char *target_get_name(struct target_s *target)
518 return target->type->name;
521 static int target_write_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
523 if (!target_was_examined(target))
525 LOG_ERROR("Target not examined yet");
526 return ERROR_FAIL;
528 return target->type->write_memory_imp(target, address, size, count, buffer);
531 static int target_read_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
533 if (!target_was_examined(target))
535 LOG_ERROR("Target not examined yet");
536 return ERROR_FAIL;
538 return target->type->read_memory_imp(target, address, size, count, buffer);
541 static int target_soft_reset_halt_imp(struct target_s *target)
543 if (!target_was_examined(target))
545 LOG_ERROR("Target not examined yet");
546 return ERROR_FAIL;
548 return target->type->soft_reset_halt_imp(target);
551 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)
553 if (!target_was_examined(target))
555 LOG_ERROR("Target not examined yet");
556 return ERROR_FAIL;
558 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);
561 int target_read_memory(struct target_s *target,
562 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
564 return target->type->read_memory(target, address, size, count, buffer);
567 int target_write_memory(struct target_s *target,
568 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
570 return target->type->write_memory(target, address, size, count, buffer);
572 int target_bulk_write_memory(struct target_s *target,
573 uint32_t address, uint32_t count, uint8_t *buffer)
575 return target->type->bulk_write_memory(target, address, count, buffer);
578 int target_add_breakpoint(struct target_s *target,
579 struct breakpoint_s *breakpoint)
581 return target->type->add_breakpoint(target, breakpoint);
583 int target_remove_breakpoint(struct target_s *target,
584 struct breakpoint_s *breakpoint)
586 return target->type->remove_breakpoint(target, breakpoint);
589 int target_add_watchpoint(struct target_s *target,
590 struct watchpoint_s *watchpoint)
592 return target->type->add_watchpoint(target, watchpoint);
594 int target_remove_watchpoint(struct target_s *target,
595 struct watchpoint_s *watchpoint)
597 return target->type->remove_watchpoint(target, watchpoint);
600 int target_get_gdb_reg_list(struct target_s *target,
601 struct reg_s **reg_list[], int *reg_list_size)
603 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
605 int target_step(struct target_s *target,
606 int current, uint32_t address, int handle_breakpoints)
608 return target->type->step(target, current, address, handle_breakpoints);
612 int target_run_algorithm(struct target_s *target,
613 int num_mem_params, mem_param_t *mem_params,
614 int num_reg_params, reg_param_t *reg_param,
615 uint32_t entry_point, uint32_t exit_point,
616 int timeout_ms, void *arch_info)
618 return target->type->run_algorithm(target,
619 num_mem_params, mem_params, num_reg_params, reg_param,
620 entry_point, exit_point, timeout_ms, arch_info);
623 /// @returns @c true if the target has been examined.
624 bool target_was_examined(struct target_s *target)
626 return target->type->examined;
628 /// Sets the @c examined flag for the given target.
629 void target_set_examined(struct target_s *target)
631 target->type->examined = true;
633 // Reset the @c examined flag for the given target.
634 void target_reset_examined(struct target_s *target)
636 target->type->examined = false;
640 int target_init(struct command_context_s *cmd_ctx)
642 target_t *target = all_targets;
643 int retval;
645 while (target)
647 target_reset_examined(target);
648 if (target->type->examine == NULL)
650 target->type->examine = default_examine;
653 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
655 LOG_ERROR("target '%s' init failed", target_get_name(target));
656 return retval;
659 /* Set up default functions if none are provided by target */
660 if (target->type->virt2phys == NULL)
662 target->type->virt2phys = default_virt2phys;
664 target->type->virt2phys = default_virt2phys;
665 /* a non-invasive way(in terms of patches) to add some code that
666 * runs before the type->write/read_memory implementation
668 target->type->write_memory_imp = target->type->write_memory;
669 target->type->write_memory = target_write_memory_imp;
670 target->type->read_memory_imp = target->type->read_memory;
671 target->type->read_memory = target_read_memory_imp;
672 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
673 target->type->soft_reset_halt = target_soft_reset_halt_imp;
674 target->type->run_algorithm_imp = target->type->run_algorithm;
675 target->type->run_algorithm = target_run_algorithm_imp;
677 if (target->type->mmu == NULL)
679 target->type->mmu = default_mmu;
681 target = target->next;
684 if (all_targets)
686 if((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
687 return retval;
688 if((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
689 return retval;
692 return ERROR_OK;
695 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
697 target_event_callback_t **callbacks_p = &target_event_callbacks;
699 if (callback == NULL)
701 return ERROR_INVALID_ARGUMENTS;
704 if (*callbacks_p)
706 while ((*callbacks_p)->next)
707 callbacks_p = &((*callbacks_p)->next);
708 callbacks_p = &((*callbacks_p)->next);
711 (*callbacks_p) = malloc(sizeof(target_event_callback_t));
712 (*callbacks_p)->callback = callback;
713 (*callbacks_p)->priv = priv;
714 (*callbacks_p)->next = NULL;
716 return ERROR_OK;
719 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
721 target_timer_callback_t **callbacks_p = &target_timer_callbacks;
722 struct timeval now;
724 if (callback == NULL)
726 return ERROR_INVALID_ARGUMENTS;
729 if (*callbacks_p)
731 while ((*callbacks_p)->next)
732 callbacks_p = &((*callbacks_p)->next);
733 callbacks_p = &((*callbacks_p)->next);
736 (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
737 (*callbacks_p)->callback = callback;
738 (*callbacks_p)->periodic = periodic;
739 (*callbacks_p)->time_ms = time_ms;
741 gettimeofday(&now, NULL);
742 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
743 time_ms -= (time_ms % 1000);
744 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
745 if ((*callbacks_p)->when.tv_usec > 1000000)
747 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
748 (*callbacks_p)->when.tv_sec += 1;
751 (*callbacks_p)->priv = priv;
752 (*callbacks_p)->next = NULL;
754 return ERROR_OK;
757 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
759 target_event_callback_t **p = &target_event_callbacks;
760 target_event_callback_t *c = target_event_callbacks;
762 if (callback == NULL)
764 return ERROR_INVALID_ARGUMENTS;
767 while (c)
769 target_event_callback_t *next = c->next;
770 if ((c->callback == callback) && (c->priv == priv))
772 *p = next;
773 free(c);
774 return ERROR_OK;
776 else
777 p = &(c->next);
778 c = next;
781 return ERROR_OK;
784 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
786 target_timer_callback_t **p = &target_timer_callbacks;
787 target_timer_callback_t *c = target_timer_callbacks;
789 if (callback == NULL)
791 return ERROR_INVALID_ARGUMENTS;
794 while (c)
796 target_timer_callback_t *next = c->next;
797 if ((c->callback == callback) && (c->priv == priv))
799 *p = next;
800 free(c);
801 return ERROR_OK;
803 else
804 p = &(c->next);
805 c = next;
808 return ERROR_OK;
811 int target_call_event_callbacks(target_t *target, enum target_event event)
813 target_event_callback_t *callback = target_event_callbacks;
814 target_event_callback_t *next_callback;
816 if (event == TARGET_EVENT_HALTED)
818 /* execute early halted first */
819 target_call_event_callbacks(target, TARGET_EVENT_EARLY_HALTED);
822 LOG_DEBUG("target event %i (%s)",
823 event,
824 Jim_Nvp_value2name_simple( nvp_target_event, event )->name );
826 target_handle_event( target, event );
828 while (callback)
830 next_callback = callback->next;
831 callback->callback(target, event, callback->priv);
832 callback = next_callback;
835 return ERROR_OK;
838 static int target_timer_callback_periodic_restart(
839 target_timer_callback_t *cb, struct timeval *now)
841 int time_ms = cb->time_ms;
842 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
843 time_ms -= (time_ms % 1000);
844 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
845 if (cb->when.tv_usec > 1000000)
847 cb->when.tv_usec = cb->when.tv_usec - 1000000;
848 cb->when.tv_sec += 1;
850 return ERROR_OK;
853 static int target_call_timer_callback(target_timer_callback_t *cb,
854 struct timeval *now)
856 cb->callback(cb->priv);
858 if (cb->periodic)
859 return target_timer_callback_periodic_restart(cb, now);
861 return target_unregister_timer_callback(cb->callback, cb->priv);
864 static int target_call_timer_callbacks_check_time(int checktime)
866 keep_alive();
868 struct timeval now;
869 gettimeofday(&now, NULL);
871 target_timer_callback_t *callback = target_timer_callbacks;
872 while (callback)
874 // cleaning up may unregister and free this callback
875 target_timer_callback_t *next_callback = callback->next;
877 bool call_it = callback->callback &&
878 ((!checktime && callback->periodic) ||
879 now.tv_sec > callback->when.tv_sec ||
880 (now.tv_sec == callback->when.tv_sec &&
881 now.tv_usec >= callback->when.tv_usec));
883 if (call_it)
885 int retval = target_call_timer_callback(callback, &now);
886 if (retval != ERROR_OK)
887 return retval;
890 callback = next_callback;
893 return ERROR_OK;
896 int target_call_timer_callbacks(void)
898 return target_call_timer_callbacks_check_time(1);
901 /* invoke periodic callbacks immediately */
902 int target_call_timer_callbacks_now(void)
904 return target_call_timer_callbacks_check_time(0);
907 int target_alloc_working_area(struct target_s *target, uint32_t size, working_area_t **area)
909 working_area_t *c = target->working_areas;
910 working_area_t *new_wa = NULL;
912 /* Reevaluate working area address based on MMU state*/
913 if (target->working_areas == NULL)
915 int retval;
916 int enabled;
917 retval = target->type->mmu(target, &enabled);
918 if (retval != ERROR_OK)
920 return retval;
922 if (enabled)
924 target->working_area = target->working_area_virt;
926 else
928 target->working_area = target->working_area_phys;
932 /* only allocate multiples of 4 byte */
933 if (size % 4)
935 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes, padding");
936 size = CEIL(size, 4);
939 /* see if there's already a matching working area */
940 while (c)
942 if ((c->free) && (c->size == size))
944 new_wa = c;
945 break;
947 c = c->next;
950 /* if not, allocate a new one */
951 if (!new_wa)
953 working_area_t **p = &target->working_areas;
954 uint32_t first_free = target->working_area;
955 uint32_t free_size = target->working_area_size;
957 LOG_DEBUG("allocating new working area");
959 c = target->working_areas;
960 while (c)
962 first_free += c->size;
963 free_size -= c->size;
964 p = &c->next;
965 c = c->next;
968 if (free_size < size)
970 LOG_WARNING("not enough working area available(requested %d, free %d)", size, free_size);
971 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
974 new_wa = malloc(sizeof(working_area_t));
975 new_wa->next = NULL;
976 new_wa->size = size;
977 new_wa->address = first_free;
979 if (target->backup_working_area)
981 int retval;
982 new_wa->backup = malloc(new_wa->size);
983 if((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
985 free(new_wa->backup);
986 free(new_wa);
987 return retval;
990 else
992 new_wa->backup = NULL;
995 /* put new entry in list */
996 *p = new_wa;
999 /* mark as used, and return the new (reused) area */
1000 new_wa->free = 0;
1001 *area = new_wa;
1003 /* user pointer */
1004 new_wa->user = area;
1006 return ERROR_OK;
1009 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
1011 if (area->free)
1012 return ERROR_OK;
1014 if (restore&&target->backup_working_area)
1016 int retval;
1017 if((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1018 return retval;
1021 area->free = 1;
1023 /* mark user pointer invalid */
1024 *area->user = NULL;
1025 area->user = NULL;
1027 return ERROR_OK;
1030 int target_free_working_area(struct target_s *target, working_area_t *area)
1032 return target_free_working_area_restore(target, area, 1);
1035 /* free resources and restore memory, if restoring memory fails,
1036 * free up resources anyway
1038 void target_free_all_working_areas_restore(struct target_s *target, int restore)
1040 working_area_t *c = target->working_areas;
1042 while (c)
1044 working_area_t *next = c->next;
1045 target_free_working_area_restore(target, c, restore);
1047 if (c->backup)
1048 free(c->backup);
1050 free(c);
1052 c = next;
1055 target->working_areas = NULL;
1058 void target_free_all_working_areas(struct target_s *target)
1060 target_free_all_working_areas_restore(target, 1);
1063 int target_register_commands(struct command_context_s *cmd_ctx)
1066 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)");
1071 register_jim(cmd_ctx, "target", jim_target, "configure target" );
1073 return ERROR_OK;
1076 int target_arch_state(struct target_s *target)
1078 int retval;
1079 if (target==NULL)
1081 LOG_USER("No target has been configured");
1082 return ERROR_OK;
1085 LOG_USER("target state: %s",
1086 Jim_Nvp_value2name_simple(nvp_target_state,target->state)->name);
1088 if (target->state!=TARGET_HALTED)
1089 return ERROR_OK;
1091 retval=target->type->arch_state(target);
1092 return retval;
1095 /* Single aligned words are guaranteed to use 16 or 32 bit access
1096 * mode respectively, otherwise data is handled as quickly as
1097 * possible
1099 int target_write_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1101 int retval;
1102 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x", size, address);
1104 if (!target_was_examined(target))
1106 LOG_ERROR("Target not examined yet");
1107 return ERROR_FAIL;
1110 if (size == 0) {
1111 return ERROR_OK;
1114 if ((address + size - 1) < address)
1116 /* GDB can request this when e.g. PC is 0xfffffffc*/
1117 LOG_ERROR("address+size wrapped(0x%08x, 0x%08x)", address, size);
1118 return ERROR_FAIL;
1121 if (((address % 2) == 0) && (size == 2))
1123 return target_write_memory(target, address, 2, 1, buffer);
1126 /* handle unaligned head bytes */
1127 if (address % 4)
1129 uint32_t unaligned = 4 - (address % 4);
1131 if (unaligned > size)
1132 unaligned = size;
1134 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1135 return retval;
1137 buffer += unaligned;
1138 address += unaligned;
1139 size -= unaligned;
1142 /* handle aligned words */
1143 if (size >= 4)
1145 int aligned = size - (size % 4);
1147 /* use bulk writes above a certain limit. This may have to be changed */
1148 if (aligned > 128)
1150 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1151 return retval;
1153 else
1155 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1156 return retval;
1159 buffer += aligned;
1160 address += aligned;
1161 size -= aligned;
1164 /* handle tail writes of less than 4 bytes */
1165 if (size > 0)
1167 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1168 return retval;
1171 return ERROR_OK;
1174 /* Single aligned words are guaranteed to use 16 or 32 bit access
1175 * mode respectively, otherwise data is handled as quickly as
1176 * possible
1178 int target_read_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1180 int retval;
1181 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x", size, address);
1183 if (!target_was_examined(target))
1185 LOG_ERROR("Target not examined yet");
1186 return ERROR_FAIL;
1189 if (size == 0) {
1190 return ERROR_OK;
1193 if ((address + size - 1) < address)
1195 /* GDB can request this when e.g. PC is 0xfffffffc*/
1196 LOG_ERROR("address+size wrapped(0x%08x, 0x%08x)", address, size);
1197 return ERROR_FAIL;
1200 if (((address % 2) == 0) && (size == 2))
1202 return target_read_memory(target, address, 2, 1, buffer);
1205 /* handle unaligned head bytes */
1206 if (address % 4)
1208 uint32_t unaligned = 4 - (address % 4);
1210 if (unaligned > size)
1211 unaligned = size;
1213 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1214 return retval;
1216 buffer += unaligned;
1217 address += unaligned;
1218 size -= unaligned;
1221 /* handle aligned words */
1222 if (size >= 4)
1224 int aligned = size - (size % 4);
1226 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1227 return retval;
1229 buffer += aligned;
1230 address += aligned;
1231 size -= aligned;
1234 /* handle tail writes of less than 4 bytes */
1235 if (size > 0)
1237 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1238 return retval;
1241 return ERROR_OK;
1244 int target_checksum_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* crc)
1246 uint8_t *buffer;
1247 int retval;
1248 uint32_t i;
1249 uint32_t checksum = 0;
1250 if (!target_was_examined(target))
1252 LOG_ERROR("Target not examined yet");
1253 return ERROR_FAIL;
1256 if ((retval = target->type->checksum_memory(target, address,
1257 size, &checksum)) != ERROR_OK)
1259 buffer = malloc(size);
1260 if (buffer == NULL)
1262 LOG_ERROR("error allocating buffer for section (%d bytes)", size);
1263 return ERROR_INVALID_ARGUMENTS;
1265 retval = target_read_buffer(target, address, size, buffer);
1266 if (retval != ERROR_OK)
1268 free(buffer);
1269 return retval;
1272 /* convert to target endianess */
1273 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1275 uint32_t target_data;
1276 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1277 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1280 retval = image_calculate_checksum( buffer, size, &checksum );
1281 free(buffer);
1284 *crc = checksum;
1286 return retval;
1289 int target_blank_check_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* blank)
1291 int retval;
1292 if (!target_was_examined(target))
1294 LOG_ERROR("Target not examined yet");
1295 return ERROR_FAIL;
1298 if (target->type->blank_check_memory == 0)
1299 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1301 retval = target->type->blank_check_memory(target, address, size, blank);
1303 return retval;
1306 int target_read_u32(struct target_s *target, uint32_t address, uint32_t *value)
1308 uint8_t value_buf[4];
1309 if (!target_was_examined(target))
1311 LOG_ERROR("Target not examined yet");
1312 return ERROR_FAIL;
1315 int retval = target_read_memory(target, address, 4, 1, value_buf);
1317 if (retval == ERROR_OK)
1319 *value = target_buffer_get_u32(target, value_buf);
1320 LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, *value);
1322 else
1324 *value = 0x0;
1325 LOG_DEBUG("address: 0x%8.8x failed", address);
1328 return retval;
1331 int target_read_u16(struct target_s *target, uint32_t address, uint16_t *value)
1333 uint8_t value_buf[2];
1334 if (!target_was_examined(target))
1336 LOG_ERROR("Target not examined yet");
1337 return ERROR_FAIL;
1340 int retval = target_read_memory(target, address, 2, 1, value_buf);
1342 if (retval == ERROR_OK)
1344 *value = target_buffer_get_u16(target, value_buf);
1345 LOG_DEBUG("address: 0x%8.8x, value: 0x%4.4x", address, *value);
1347 else
1349 *value = 0x0;
1350 LOG_DEBUG("address: 0x%8.8x failed", address);
1353 return retval;
1356 int target_read_u8(struct target_s *target, uint32_t address, uint8_t *value)
1358 int retval = target_read_memory(target, address, 1, 1, value);
1359 if (!target_was_examined(target))
1361 LOG_ERROR("Target not examined yet");
1362 return ERROR_FAIL;
1365 if (retval == ERROR_OK)
1367 LOG_DEBUG("address: 0x%8.8x, value: 0x%2.2x", address, *value);
1369 else
1371 *value = 0x0;
1372 LOG_DEBUG("address: 0x%8.8x failed", address);
1375 return retval;
1378 int target_write_u32(struct target_s *target, uint32_t address, uint32_t value)
1380 int retval;
1381 uint8_t value_buf[4];
1382 if (!target_was_examined(target))
1384 LOG_ERROR("Target not examined yet");
1385 return ERROR_FAIL;
1388 LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, value);
1390 target_buffer_set_u32(target, value_buf, value);
1391 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1393 LOG_DEBUG("failed: %i", retval);
1396 return retval;
1399 int target_write_u16(struct target_s *target, uint32_t address, uint16_t value)
1401 int retval;
1402 uint8_t value_buf[2];
1403 if (!target_was_examined(target))
1405 LOG_ERROR("Target not examined yet");
1406 return ERROR_FAIL;
1409 LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, value);
1411 target_buffer_set_u16(target, value_buf, value);
1412 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1414 LOG_DEBUG("failed: %i", retval);
1417 return retval;
1420 int target_write_u8(struct target_s *target, uint32_t address, uint8_t value)
1422 int retval;
1423 if (!target_was_examined(target))
1425 LOG_ERROR("Target not examined yet");
1426 return ERROR_FAIL;
1429 LOG_DEBUG("address: 0x%8.8x, value: 0x%2.2x", address, value);
1431 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1433 LOG_DEBUG("failed: %i", retval);
1436 return retval;
1439 int target_register_user_commands(struct command_context_s *cmd_ctx)
1441 int retval = ERROR_OK;
1444 /* script procedures */
1445 register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "profiling samples the CPU PC");
1446 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>");
1447 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>");
1449 register_command(cmd_ctx, NULL, "fast_load_image", handle_fast_load_image_command, COMMAND_ANY,
1450 "same args as load_image, image stored in memory - mainly for profiling purposes");
1452 register_command(cmd_ctx, NULL, "fast_load", handle_fast_load_command, COMMAND_ANY,
1453 "loads active fast load image to current target - mainly for profiling purposes");
1456 register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "translate a virtual address into a physical address");
1457 register_command(cmd_ctx, NULL, "reg", handle_reg_command, COMMAND_EXEC, "display or set a register");
1458 register_command(cmd_ctx, NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1459 register_command(cmd_ctx, NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1460 register_command(cmd_ctx, NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1461 register_command(cmd_ctx, NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1462 register_command(cmd_ctx, NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1463 register_command(cmd_ctx, NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run|halt|init] - default is run");
1464 register_command(cmd_ctx, NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1466 register_command(cmd_ctx, NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words <addr> [count]");
1467 register_command(cmd_ctx, NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words <addr> [count]");
1468 register_command(cmd_ctx, NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes <addr> [count]");
1470 register_command(cmd_ctx, NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word <addr> <value> [count]");
1471 register_command(cmd_ctx, NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word <addr> <value> [count]");
1472 register_command(cmd_ctx, NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte <addr> <value> [count]");
1474 register_command(cmd_ctx, NULL, "bp", handle_bp_command, COMMAND_EXEC, "set breakpoint <address> <length> [hw]");
1475 register_command(cmd_ctx, NULL, "rbp", handle_rbp_command, COMMAND_EXEC, "remove breakpoint <adress>");
1476 register_command(cmd_ctx, NULL, "wp", handle_wp_command, COMMAND_EXEC, "set watchpoint <address> <length> <r/w/a> [value] [mask]");
1477 register_command(cmd_ctx, NULL, "rwp", handle_rwp_command, COMMAND_EXEC, "remove watchpoint <adress>");
1479 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]");
1480 register_command(cmd_ctx, NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1481 register_command(cmd_ctx, NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1482 register_command(cmd_ctx, NULL, "test_image", handle_test_image_command, COMMAND_EXEC, "test_image <file> [offset] [type]");
1484 if((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
1485 return retval;
1486 if((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
1487 return retval;
1489 return retval;
1492 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1494 target_t *target = all_targets;
1496 if (argc == 1)
1498 target = get_target(args[0]);
1499 if (target == NULL) {
1500 command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0] );
1501 goto DumpTargets;
1503 if (!target->tap->enabled) {
1504 command_print(cmd_ctx,"Target: TAP %s is disabled, "
1505 "can't be the current target\n",
1506 target->tap->dotted_name);
1507 return ERROR_FAIL;
1510 cmd_ctx->current_target = target->target_number;
1511 return ERROR_OK;
1513 DumpTargets:
1515 target = all_targets;
1516 command_print(cmd_ctx, " TargetName Type Endian TapName State ");
1517 command_print(cmd_ctx, "-- ------------------ ---------- ------ ------------------ ------------");
1518 while (target)
1520 const char *state;
1521 char marker = ' ';
1523 if (target->tap->enabled)
1524 state = Jim_Nvp_value2name_simple(nvp_target_state,
1525 target->state)->name;
1526 else
1527 state = "tap-disabled";
1529 if (cmd_ctx->current_target == target->target_number)
1530 marker = '*';
1532 /* keep columns lined up to match the headers above */
1533 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1534 target->target_number,
1535 marker,
1536 target->cmd_name,
1537 target_get_name(target),
1538 Jim_Nvp_value2name_simple(nvp_target_endian,
1539 target->endianness)->name,
1540 target->tap->dotted_name,
1541 state);
1542 target = target->next;
1545 return ERROR_OK;
1548 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1550 static int powerDropout;
1551 static int srstAsserted;
1553 static int runPowerRestore;
1554 static int runPowerDropout;
1555 static int runSrstAsserted;
1556 static int runSrstDeasserted;
1558 static int sense_handler(void)
1560 static int prevSrstAsserted = 0;
1561 static int prevPowerdropout = 0;
1563 int retval;
1564 if ((retval=jtag_power_dropout(&powerDropout))!=ERROR_OK)
1565 return retval;
1567 int powerRestored;
1568 powerRestored = prevPowerdropout && !powerDropout;
1569 if (powerRestored)
1571 runPowerRestore = 1;
1574 long long current = timeval_ms();
1575 static long long lastPower = 0;
1576 int waitMore = lastPower + 2000 > current;
1577 if (powerDropout && !waitMore)
1579 runPowerDropout = 1;
1580 lastPower = current;
1583 if ((retval=jtag_srst_asserted(&srstAsserted))!=ERROR_OK)
1584 return retval;
1586 int srstDeasserted;
1587 srstDeasserted = prevSrstAsserted && !srstAsserted;
1589 static long long lastSrst = 0;
1590 waitMore = lastSrst + 2000 > current;
1591 if (srstDeasserted && !waitMore)
1593 runSrstDeasserted = 1;
1594 lastSrst = current;
1597 if (!prevSrstAsserted && srstAsserted)
1599 runSrstAsserted = 1;
1602 prevSrstAsserted = srstAsserted;
1603 prevPowerdropout = powerDropout;
1605 if (srstDeasserted || powerRestored)
1607 /* Other than logging the event we can't do anything here.
1608 * Issuing a reset is a particularly bad idea as we might
1609 * be inside a reset already.
1613 return ERROR_OK;
1616 /* process target state changes */
1617 int handle_target(void *priv)
1619 int retval = ERROR_OK;
1621 /* we do not want to recurse here... */
1622 static int recursive = 0;
1623 if (! recursive)
1625 recursive = 1;
1626 sense_handler();
1627 /* danger! running these procedures can trigger srst assertions and power dropouts.
1628 * We need to avoid an infinite loop/recursion here and we do that by
1629 * clearing the flags after running these events.
1631 int did_something = 0;
1632 if (runSrstAsserted)
1634 Jim_Eval( interp, "srst_asserted");
1635 did_something = 1;
1637 if (runSrstDeasserted)
1639 Jim_Eval( interp, "srst_deasserted");
1640 did_something = 1;
1642 if (runPowerDropout)
1644 Jim_Eval( interp, "power_dropout");
1645 did_something = 1;
1647 if (runPowerRestore)
1649 Jim_Eval( interp, "power_restore");
1650 did_something = 1;
1653 if (did_something)
1655 /* clear detect flags */
1656 sense_handler();
1659 /* clear action flags */
1661 runSrstAsserted=0;
1662 runSrstDeasserted=0;
1663 runPowerRestore=0;
1664 runPowerDropout=0;
1666 recursive = 0;
1669 /* Poll targets for state changes unless that's globally disabled.
1670 * Skip targets that are currently disabled.
1672 for (target_t *target = all_targets;
1673 target_continuous_poll && target;
1674 target = target->next)
1676 if (!target->tap->enabled)
1677 continue;
1679 /* only poll target if we've got power and srst isn't asserted */
1680 if (!powerDropout && !srstAsserted)
1682 /* polling may fail silently until the target has been examined */
1683 if((retval = target_poll(target)) != ERROR_OK)
1684 return retval;
1688 return retval;
1691 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1693 target_t *target;
1694 reg_t *reg = NULL;
1695 int count = 0;
1696 char *value;
1698 LOG_DEBUG("-");
1700 target = get_current_target(cmd_ctx);
1702 /* list all available registers for the current target */
1703 if (argc == 0)
1705 reg_cache_t *cache = target->reg_cache;
1707 count = 0;
1708 while(cache)
1710 int i;
1711 for (i = 0; i < cache->num_regs; i++)
1713 value = buf_to_str(cache->reg_list[i].value, cache->reg_list[i].size, 16);
1714 command_print(cmd_ctx, "(%i) %s (/%i): 0x%s (dirty: %i, valid: %i)", count++, cache->reg_list[i].name, cache->reg_list[i].size, value, cache->reg_list[i].dirty, cache->reg_list[i].valid);
1715 free(value);
1717 cache = cache->next;
1720 return ERROR_OK;
1723 /* access a single register by its ordinal number */
1724 if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1726 unsigned num;
1727 int retval = parse_uint(args[0], &num);
1728 if (ERROR_OK != retval)
1729 return ERROR_COMMAND_SYNTAX_ERROR;
1731 reg_cache_t *cache = target->reg_cache;
1732 count = 0;
1733 while(cache)
1735 int i;
1736 for (i = 0; i < cache->num_regs; i++)
1738 if (count++ == (int)num)
1740 reg = &cache->reg_list[i];
1741 break;
1744 if (reg)
1745 break;
1746 cache = cache->next;
1749 if (!reg)
1751 command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1752 return ERROR_OK;
1754 } else /* access a single register by its name */
1756 reg = register_get_by_name(target->reg_cache, args[0], 1);
1758 if (!reg)
1760 command_print(cmd_ctx, "register %s not found in current target", args[0]);
1761 return ERROR_OK;
1765 /* display a register */
1766 if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1768 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1769 reg->valid = 0;
1771 if (reg->valid == 0)
1773 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1774 arch_type->get(reg);
1776 value = buf_to_str(reg->value, reg->size, 16);
1777 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, reg->size, value);
1778 free(value);
1779 return ERROR_OK;
1782 /* set register value */
1783 if (argc == 2)
1785 uint8_t *buf = malloc(CEIL(reg->size, 8));
1786 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1788 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1789 arch_type->set(reg, buf);
1791 value = buf_to_str(reg->value, reg->size, 16);
1792 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, reg->size, value);
1793 free(value);
1795 free(buf);
1797 return ERROR_OK;
1800 command_print(cmd_ctx, "usage: reg <#|name> [value]");
1802 return ERROR_OK;
1805 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1807 int retval = ERROR_OK;
1808 target_t *target = get_current_target(cmd_ctx);
1810 if (argc == 0)
1812 command_print(cmd_ctx, "background polling: %s",
1813 target_continuous_poll ? "on" : "off");
1814 command_print(cmd_ctx, "TAP: %s (%s)",
1815 target->tap->dotted_name,
1816 target->tap->enabled ? "enabled" : "disabled");
1817 if (!target->tap->enabled)
1818 return ERROR_OK;
1819 if ((retval = target_poll(target)) != ERROR_OK)
1820 return retval;
1821 if ((retval = target_arch_state(target)) != ERROR_OK)
1822 return retval;
1825 else if (argc==1)
1827 if (strcmp(args[0], "on") == 0)
1829 target_continuous_poll = 1;
1831 else if (strcmp(args[0], "off") == 0)
1833 target_continuous_poll = 0;
1835 else
1837 command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1839 } else
1841 return ERROR_COMMAND_SYNTAX_ERROR;
1844 return retval;
1847 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1849 if (argc > 1)
1850 return ERROR_COMMAND_SYNTAX_ERROR;
1852 unsigned ms = 5000;
1853 if (1 == argc)
1855 int retval = parse_uint(args[0], &ms);
1856 if (ERROR_OK != retval)
1858 command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1859 return ERROR_COMMAND_SYNTAX_ERROR;
1861 // convert seconds (given) to milliseconds (needed)
1862 ms *= 1000;
1865 target_t *target = get_current_target(cmd_ctx);
1866 return target_wait_state(target, TARGET_HALTED, ms);
1869 /* wait for target state to change. The trick here is to have a low
1870 * latency for short waits and not to suck up all the CPU time
1871 * on longer waits.
1873 * After 500ms, keep_alive() is invoked
1875 int target_wait_state(target_t *target, enum target_state state, int ms)
1877 int retval;
1878 long long then=0, cur;
1879 int once=1;
1881 for (;;)
1883 if ((retval=target_poll(target))!=ERROR_OK)
1884 return retval;
1885 if (target->state == state)
1887 break;
1889 cur = timeval_ms();
1890 if (once)
1892 once=0;
1893 then = timeval_ms();
1894 LOG_DEBUG("waiting for target %s...",
1895 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1898 if (cur-then>500)
1900 keep_alive();
1903 if ((cur-then)>ms)
1905 LOG_ERROR("timed out while waiting for target %s",
1906 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1907 return ERROR_FAIL;
1911 return ERROR_OK;
1914 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1916 LOG_DEBUG("-");
1918 target_t *target = get_current_target(cmd_ctx);
1919 int retval = target_halt(target);
1920 if (ERROR_OK != retval)
1921 return retval;
1923 if (argc == 1)
1925 unsigned wait;
1926 retval = parse_uint(args[0], &wait);
1927 if (ERROR_OK != retval)
1928 return ERROR_COMMAND_SYNTAX_ERROR;
1929 if (!wait)
1930 return ERROR_OK;
1933 return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
1936 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1938 target_t *target = get_current_target(cmd_ctx);
1940 LOG_USER("requesting target halt and executing a soft reset");
1942 target->type->soft_reset_halt(target);
1944 return ERROR_OK;
1947 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1949 if (argc > 1)
1950 return ERROR_COMMAND_SYNTAX_ERROR;
1952 enum target_reset_mode reset_mode = RESET_RUN;
1953 if (argc == 1)
1955 const Jim_Nvp *n;
1956 n = Jim_Nvp_name2value_simple( nvp_reset_modes, args[0] );
1957 if( (n->name == NULL) || (n->value == RESET_UNKNOWN) ){
1958 return ERROR_COMMAND_SYNTAX_ERROR;
1960 reset_mode = n->value;
1963 /* reset *all* targets */
1964 return target_process_reset(cmd_ctx, reset_mode);
1968 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1970 if (argc > 1)
1971 return ERROR_COMMAND_SYNTAX_ERROR;
1973 target_t *target = get_current_target(cmd_ctx);
1974 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
1976 /* with no args, resume from current pc, addr = 0,
1977 * with one arguments, addr = args[0],
1978 * handle breakpoints, not debugging */
1979 uint32_t addr = 0;
1980 if (argc == 1)
1982 int retval = parse_u32(args[0], &addr);
1983 if (ERROR_OK != retval)
1984 return retval;
1987 return target_resume(target, 0, addr, 1, 0);
1990 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1992 if (argc > 1)
1993 return ERROR_COMMAND_SYNTAX_ERROR;
1995 LOG_DEBUG("-");
1997 /* with no args, step from current pc, addr = 0,
1998 * with one argument addr = args[0],
1999 * handle breakpoints, debugging */
2000 uint32_t addr = 0;
2001 if (argc == 1)
2003 int retval = parse_u32(args[0], &addr);
2004 if (ERROR_OK != retval)
2005 return retval;
2008 target_t *target = get_current_target(cmd_ctx);
2009 return target->type->step(target, 0, addr, 1);
2012 static void handle_md_output(struct command_context_s *cmd_ctx,
2013 struct target_s *target, uint32_t address, unsigned size,
2014 unsigned count, const uint8_t *buffer)
2016 const unsigned line_bytecnt = 32;
2017 unsigned line_modulo = line_bytecnt / size;
2019 char output[line_bytecnt * 4 + 1];
2020 unsigned output_len = 0;
2022 const char *value_fmt;
2023 switch (size) {
2024 case 4: value_fmt = "%8.8x "; break;
2025 case 2: value_fmt = "%4.2x "; break;
2026 case 1: value_fmt = "%2.2x "; break;
2027 default:
2028 LOG_ERROR("invalid memory read size: %u", size);
2029 exit(-1);
2032 for (unsigned i = 0; i < count; i++)
2034 if (i % line_modulo == 0)
2036 output_len += snprintf(output + output_len,
2037 sizeof(output) - output_len,
2038 "0x%8.8x: ", address + (i*size));
2041 uint32_t value=0;
2042 const uint8_t *value_ptr = buffer + i * size;
2043 switch (size) {
2044 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2045 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2046 case 1: value = *value_ptr;
2048 output_len += snprintf(output + output_len,
2049 sizeof(output) - output_len,
2050 value_fmt, value);
2052 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2054 command_print(cmd_ctx, "%s", output);
2055 output_len = 0;
2060 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2062 if (argc < 1)
2063 return ERROR_COMMAND_SYNTAX_ERROR;
2065 unsigned size = 0;
2066 switch (cmd[2]) {
2067 case 'w': size = 4; break;
2068 case 'h': size = 2; break;
2069 case 'b': size = 1; break;
2070 default: return ERROR_COMMAND_SYNTAX_ERROR;
2073 uint32_t address;
2074 int retval = parse_u32(args[0], &address);
2075 if (ERROR_OK != retval)
2076 return retval;
2078 unsigned count = 1;
2079 if (argc == 2)
2081 retval = parse_uint(args[1], &count);
2082 if (ERROR_OK != retval)
2083 return retval;
2086 uint8_t *buffer = calloc(count, size);
2088 target_t *target = get_current_target(cmd_ctx);
2089 retval = target_read_memory(target,
2090 address, size, count, buffer);
2091 if (ERROR_OK == retval)
2092 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2094 free(buffer);
2096 return retval;
2099 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2101 if ((argc < 2) || (argc > 3))
2102 return ERROR_COMMAND_SYNTAX_ERROR;
2104 uint32_t address;
2105 int retval = parse_u32(args[0], &address);
2106 if (ERROR_OK != retval)
2107 return retval;
2109 uint32_t value;
2110 retval = parse_u32(args[1], &value);
2111 if (ERROR_OK != retval)
2112 return retval;
2114 unsigned count = 1;
2115 if (argc == 3)
2117 retval = parse_uint(args[2], &count);
2118 if (ERROR_OK != retval)
2119 return retval;
2122 target_t *target = get_current_target(cmd_ctx);
2123 unsigned wordsize;
2124 uint8_t value_buf[4];
2125 switch (cmd[2])
2127 case 'w':
2128 wordsize = 4;
2129 target_buffer_set_u32(target, value_buf, value);
2130 break;
2131 case 'h':
2132 wordsize = 2;
2133 target_buffer_set_u16(target, value_buf, value);
2134 break;
2135 case 'b':
2136 wordsize = 1;
2137 value_buf[0] = value;
2138 break;
2139 default:
2140 return ERROR_COMMAND_SYNTAX_ERROR;
2142 for (unsigned i = 0; i < count; i++)
2144 retval = target_write_memory(target,
2145 address + i * wordsize, wordsize, 1, value_buf);
2146 if (ERROR_OK != retval)
2147 return retval;
2148 keep_alive();
2151 return ERROR_OK;
2155 static int parse_load_image_command_args(char **args, int argc,
2156 image_t *image, uint32_t *min_address, uint32_t *max_address)
2158 if (argc < 1 || argc > 5)
2159 return ERROR_COMMAND_SYNTAX_ERROR;
2161 /* a base address isn't always necessary,
2162 * default to 0x0 (i.e. don't relocate) */
2163 if (argc >= 2)
2165 uint32_t addr;
2166 int retval = parse_u32(args[1], &addr);
2167 if (ERROR_OK != retval)
2168 return ERROR_COMMAND_SYNTAX_ERROR;
2169 image->base_address = addr;
2170 image->base_address_set = 1;
2172 else
2173 image->base_address_set = 0;
2175 image->start_address_set = 0;
2177 if (argc >= 4)
2179 int retval = parse_u32(args[3], min_address);
2180 if (ERROR_OK != retval)
2181 return ERROR_COMMAND_SYNTAX_ERROR;
2183 if (argc == 5)
2185 int retval = parse_u32(args[4], max_address);
2186 if (ERROR_OK != retval)
2187 return ERROR_COMMAND_SYNTAX_ERROR;
2188 // use size (given) to find max (required)
2189 *max_address += *min_address;
2192 if (*min_address > *max_address)
2193 return ERROR_COMMAND_SYNTAX_ERROR;
2195 return ERROR_OK;
2198 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2200 uint8_t *buffer;
2201 uint32_t buf_cnt;
2202 uint32_t image_size;
2203 uint32_t min_address = 0;
2204 uint32_t max_address = 0xffffffff;
2205 int i;
2206 int retvaltemp;
2208 image_t image;
2210 duration_t duration;
2211 char *duration_text;
2213 int retval = parse_load_image_command_args(args, argc,
2214 &image, &min_address, &max_address);
2215 if (ERROR_OK != retval)
2216 return retval;
2218 target_t *target = get_current_target(cmd_ctx);
2219 duration_start_measure(&duration);
2221 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2223 return ERROR_OK;
2226 image_size = 0x0;
2227 retval = ERROR_OK;
2228 for (i = 0; i < image.num_sections; i++)
2230 buffer = malloc(image.sections[i].size);
2231 if (buffer == NULL)
2233 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
2234 break;
2237 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2239 free(buffer);
2240 break;
2243 uint32_t offset=0;
2244 uint32_t length=buf_cnt;
2246 /* DANGER!!! beware of unsigned comparision here!!! */
2248 if ((image.sections[i].base_address+buf_cnt>=min_address)&&
2249 (image.sections[i].base_address<max_address))
2251 if (image.sections[i].base_address<min_address)
2253 /* clip addresses below */
2254 offset+=min_address-image.sections[i].base_address;
2255 length-=offset;
2258 if (image.sections[i].base_address+buf_cnt>max_address)
2260 length-=(image.sections[i].base_address+buf_cnt)-max_address;
2263 if ((retval = target_write_buffer(target, image.sections[i].base_address+offset, length, buffer+offset)) != ERROR_OK)
2265 free(buffer);
2266 break;
2268 image_size += length;
2269 command_print(cmd_ctx, "%u byte written at address 0x%8.8x", length, image.sections[i].base_address+offset);
2272 free(buffer);
2275 if((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2277 image_close(&image);
2278 return retvaltemp;
2281 if (retval==ERROR_OK)
2283 command_print(cmd_ctx, "downloaded %u byte in %s", image_size, duration_text);
2285 free(duration_text);
2287 image_close(&image);
2289 return retval;
2293 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2295 fileio_t fileio;
2297 uint8_t buffer[560];
2298 int retvaltemp;
2300 duration_t duration;
2301 char *duration_text;
2303 target_t *target = get_current_target(cmd_ctx);
2305 if (argc != 3)
2307 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2308 return ERROR_OK;
2311 uint32_t address;
2312 int retval = parse_u32(args[1], &address);
2313 if (ERROR_OK != retval)
2314 return retval;
2316 uint32_t size;
2317 retval = parse_u32(args[2], &size);
2318 if (ERROR_OK != retval)
2319 return retval;
2321 if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2323 return ERROR_OK;
2326 duration_start_measure(&duration);
2328 while (size > 0)
2330 uint32_t size_written;
2331 uint32_t this_run_size = (size > 560) ? 560 : size;
2333 retval = target_read_buffer(target, address, this_run_size, buffer);
2334 if (retval != ERROR_OK)
2336 break;
2339 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2340 if (retval != ERROR_OK)
2342 break;
2345 size -= this_run_size;
2346 address += this_run_size;
2349 if((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2350 return retvaltemp;
2352 if((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2353 return retvaltemp;
2355 if (retval==ERROR_OK)
2357 command_print(cmd_ctx, "dumped %lld byte in %s",
2358 fileio.size, duration_text);
2359 free(duration_text);
2362 return retval;
2365 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2367 uint8_t *buffer;
2368 uint32_t buf_cnt;
2369 uint32_t image_size;
2370 int i;
2371 int retval, retvaltemp;
2372 uint32_t checksum = 0;
2373 uint32_t mem_checksum = 0;
2375 image_t image;
2377 duration_t duration;
2378 char *duration_text;
2380 target_t *target = get_current_target(cmd_ctx);
2382 if (argc < 1)
2384 return ERROR_COMMAND_SYNTAX_ERROR;
2387 if (!target)
2389 LOG_ERROR("no target selected");
2390 return ERROR_FAIL;
2393 duration_start_measure(&duration);
2395 if (argc >= 2)
2397 uint32_t addr;
2398 retval = parse_u32(args[1], &addr);
2399 if (ERROR_OK != retval)
2400 return ERROR_COMMAND_SYNTAX_ERROR;
2401 image.base_address = addr;
2402 image.base_address_set = 1;
2404 else
2406 image.base_address_set = 0;
2407 image.base_address = 0x0;
2410 image.start_address_set = 0;
2412 if ((retval=image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2414 return retval;
2417 image_size = 0x0;
2418 retval=ERROR_OK;
2419 for (i = 0; i < image.num_sections; i++)
2421 buffer = malloc(image.sections[i].size);
2422 if (buffer == NULL)
2424 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
2425 break;
2427 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2429 free(buffer);
2430 break;
2433 if (verify)
2435 /* calculate checksum of image */
2436 image_calculate_checksum( buffer, buf_cnt, &checksum );
2438 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2439 if( retval != ERROR_OK )
2441 free(buffer);
2442 break;
2445 if( checksum != mem_checksum )
2447 /* failed crc checksum, fall back to a binary compare */
2448 uint8_t *data;
2450 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2452 data = (uint8_t*)malloc(buf_cnt);
2454 /* Can we use 32bit word accesses? */
2455 int size = 1;
2456 int count = buf_cnt;
2457 if ((count % 4) == 0)
2459 size *= 4;
2460 count /= 4;
2462 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2463 if (retval == ERROR_OK)
2465 uint32_t t;
2466 for (t = 0; t < buf_cnt; t++)
2468 if (data[t] != buffer[t])
2470 command_print(cmd_ctx, "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n", t + image.sections[i].base_address, data[t], buffer[t]);
2471 free(data);
2472 free(buffer);
2473 retval=ERROR_FAIL;
2474 goto done;
2476 if ((t%16384)==0)
2478 keep_alive();
2483 free(data);
2485 } else
2487 command_print(cmd_ctx, "address 0x%08x length 0x%08x", image.sections[i].base_address, buf_cnt);
2490 free(buffer);
2491 image_size += buf_cnt;
2493 done:
2495 if((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2497 image_close(&image);
2498 return retvaltemp;
2501 if (retval==ERROR_OK)
2503 command_print(cmd_ctx, "verified %u bytes in %s", image_size, duration_text);
2505 free(duration_text);
2507 image_close(&image);
2509 return retval;
2512 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2514 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2517 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2519 return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2522 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2524 target_t *target = get_current_target(cmd_ctx);
2525 breakpoint_t *breakpoint = target->breakpoints;
2526 while (breakpoint)
2528 if (breakpoint->type == BKPT_SOFT)
2530 char* buf = buf_to_str(breakpoint->orig_instr,
2531 breakpoint->length, 16);
2532 command_print(cmd_ctx, "0x%8.8x, 0x%x, %i, 0x%s",
2533 breakpoint->address, breakpoint->length,
2534 breakpoint->set, buf);
2535 free(buf);
2537 else
2539 command_print(cmd_ctx, "0x%8.8x, 0x%x, %i",
2540 breakpoint->address, breakpoint->length, breakpoint->set);
2543 breakpoint = breakpoint->next;
2545 return ERROR_OK;
2548 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2549 uint32_t addr, uint32_t length, int hw)
2551 target_t *target = get_current_target(cmd_ctx);
2552 int retval = breakpoint_add(target, addr, length, hw);
2553 if (ERROR_OK == retval)
2554 command_print(cmd_ctx, "breakpoint set at 0x%8.8x", addr);
2555 else
2556 LOG_ERROR("Failure setting breakpoint");
2557 return retval;
2560 static int handle_bp_command(struct command_context_s *cmd_ctx,
2561 char *cmd, char **args, int argc)
2563 if (argc == 0)
2564 return handle_bp_command_list(cmd_ctx);
2566 if (argc < 2 || argc > 3)
2568 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2569 return ERROR_COMMAND_SYNTAX_ERROR;
2572 uint32_t addr;
2573 int retval = parse_u32(args[0], &addr);
2574 if (ERROR_OK != retval)
2575 return retval;
2577 uint32_t length;
2578 retval = parse_u32(args[1], &length);
2579 if (ERROR_OK != retval)
2580 return retval;
2582 int hw = BKPT_SOFT;
2583 if (argc == 3)
2585 if (strcmp(args[2], "hw") == 0)
2586 hw = BKPT_HARD;
2587 else
2588 return ERROR_COMMAND_SYNTAX_ERROR;
2591 return handle_bp_command_set(cmd_ctx, addr, length, hw);
2594 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2596 if (argc != 1)
2597 return ERROR_COMMAND_SYNTAX_ERROR;
2599 uint32_t addr;
2600 int retval = parse_u32(args[0], &addr);
2601 if (ERROR_OK != retval)
2602 return retval;
2604 target_t *target = get_current_target(cmd_ctx);
2605 breakpoint_remove(target, addr);
2607 return ERROR_OK;
2610 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2612 target_t *target = get_current_target(cmd_ctx);
2614 if (argc == 0)
2616 watchpoint_t *watchpoint = target->watchpoints;
2618 while (watchpoint)
2620 command_print(cmd_ctx, "address: 0x%8.8x, len: 0x%8.8x, r/w/a: %i, value: 0x%8.8x, mask: 0x%8.8x", watchpoint->address, watchpoint->length, watchpoint->rw, watchpoint->value, watchpoint->mask);
2621 watchpoint = watchpoint->next;
2623 return ERROR_OK;
2626 enum watchpoint_rw type = WPT_ACCESS;
2627 uint32_t addr = 0;
2628 uint32_t length = 0;
2629 uint32_t data_value = 0x0;
2630 uint32_t data_mask = 0xffffffff;
2631 int retval;
2633 switch (argc)
2635 case 5:
2636 retval = parse_u32(args[4], &data_mask);
2637 if (ERROR_OK != retval)
2638 return retval;
2639 // fall through
2640 case 4:
2641 retval = parse_u32(args[3], &data_value);
2642 if (ERROR_OK != retval)
2643 return retval;
2644 // fall through
2645 case 3:
2646 switch(args[2][0])
2648 case 'r':
2649 type = WPT_READ;
2650 break;
2651 case 'w':
2652 type = WPT_WRITE;
2653 break;
2654 case 'a':
2655 type = WPT_ACCESS;
2656 break;
2657 default:
2658 LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2659 return ERROR_COMMAND_SYNTAX_ERROR;
2661 // fall through
2662 case 2:
2663 retval = parse_u32(args[1], &length);
2664 if (ERROR_OK != retval)
2665 return retval;
2666 retval = parse_u32(args[0], &addr);
2667 if (ERROR_OK != retval)
2668 return retval;
2669 break;
2671 default:
2672 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2673 return ERROR_COMMAND_SYNTAX_ERROR;
2676 retval = watchpoint_add(target, addr, length, type,
2677 data_value, data_mask);
2678 if (ERROR_OK != retval)
2679 LOG_ERROR("Failure setting watchpoints");
2681 return retval;
2684 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2686 if (argc != 1)
2687 return ERROR_COMMAND_SYNTAX_ERROR;
2689 uint32_t addr;
2690 int retval = parse_u32(args[0], &addr);
2691 if (ERROR_OK != retval)
2692 return retval;
2694 target_t *target = get_current_target(cmd_ctx);
2695 watchpoint_remove(target, addr);
2697 return ERROR_OK;
2702 * Translate a virtual address to a physical address.
2704 * The low-level target implementation must have logged a detailed error
2705 * which is forwarded to telnet/GDB session.
2707 static int handle_virt2phys_command(command_context_t *cmd_ctx,
2708 char *cmd, char **args, int argc)
2710 if (argc != 1)
2711 return ERROR_COMMAND_SYNTAX_ERROR;
2713 uint32_t va;
2714 int retval = parse_u32(args[0], &va);
2715 if (ERROR_OK != retval)
2716 return retval;
2717 uint32_t pa;
2719 target_t *target = get_current_target(cmd_ctx);
2720 retval = target->type->virt2phys(target, va, &pa);
2721 if (retval == ERROR_OK)
2722 command_print(cmd_ctx, "Physical address 0x%08x", pa);
2724 return retval;
2727 static void writeData(FILE *f, const void *data, size_t len)
2729 size_t written = fwrite(data, 1, len, f);
2730 if (written != len)
2731 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2734 static void writeLong(FILE *f, int l)
2736 int i;
2737 for (i=0; i<4; i++)
2739 char c=(l>>(i*8))&0xff;
2740 writeData(f, &c, 1);
2745 static void writeString(FILE *f, char *s)
2747 writeData(f, s, strlen(s));
2750 /* Dump a gmon.out histogram file. */
2751 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
2753 uint32_t i;
2754 FILE *f=fopen(filename, "w");
2755 if (f==NULL)
2756 return;
2757 writeString(f, "gmon");
2758 writeLong(f, 0x00000001); /* Version */
2759 writeLong(f, 0); /* padding */
2760 writeLong(f, 0); /* padding */
2761 writeLong(f, 0); /* padding */
2763 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
2764 writeData(f, &zero, 1);
2766 /* figure out bucket size */
2767 uint32_t min=samples[0];
2768 uint32_t max=samples[0];
2769 for (i=0; i<sampleNum; i++)
2771 if (min>samples[i])
2773 min=samples[i];
2775 if (max<samples[i])
2777 max=samples[i];
2781 int addressSpace=(max-min+1);
2783 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2784 uint32_t length = addressSpace;
2785 if (length > maxBuckets)
2787 length=maxBuckets;
2789 int *buckets=malloc(sizeof(int)*length);
2790 if (buckets==NULL)
2792 fclose(f);
2793 return;
2795 memset(buckets, 0, sizeof(int)*length);
2796 for (i=0; i<sampleNum;i++)
2798 uint32_t address=samples[i];
2799 long long a=address-min;
2800 long long b=length-1;
2801 long long c=addressSpace-1;
2802 int index=(a*b)/c; /* danger!!!! int32 overflows */
2803 buckets[index]++;
2806 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2807 writeLong(f, min); /* low_pc */
2808 writeLong(f, max); /* high_pc */
2809 writeLong(f, length); /* # of samples */
2810 writeLong(f, 64000000); /* 64MHz */
2811 writeString(f, "seconds");
2812 for (i=0; i<(15-strlen("seconds")); i++)
2813 writeData(f, &zero, 1);
2814 writeString(f, "s");
2816 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2818 char *data=malloc(2*length);
2819 if (data!=NULL)
2821 for (i=0; i<length;i++)
2823 int val;
2824 val=buckets[i];
2825 if (val>65535)
2827 val=65535;
2829 data[i*2]=val&0xff;
2830 data[i*2+1]=(val>>8)&0xff;
2832 free(buckets);
2833 writeData(f, data, length * 2);
2834 free(data);
2835 } else
2837 free(buckets);
2840 fclose(f);
2843 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2844 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2846 target_t *target = get_current_target(cmd_ctx);
2847 struct timeval timeout, now;
2849 gettimeofday(&timeout, NULL);
2850 if (argc!=2)
2852 return ERROR_COMMAND_SYNTAX_ERROR;
2854 unsigned offset;
2855 int retval = parse_uint(args[0], &offset);
2856 if (ERROR_OK != retval)
2857 return retval;
2859 timeval_add_time(&timeout, offset, 0);
2861 command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
2863 static const int maxSample=10000;
2864 uint32_t *samples=malloc(sizeof(uint32_t)*maxSample);
2865 if (samples==NULL)
2866 return ERROR_OK;
2868 int numSamples=0;
2869 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2870 reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
2872 for (;;)
2874 target_poll(target);
2875 if (target->state == TARGET_HALTED)
2877 uint32_t t=*((uint32_t *)reg->value);
2878 samples[numSamples++]=t;
2879 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2880 target_poll(target);
2881 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2882 } else if (target->state == TARGET_RUNNING)
2884 /* We want to quickly sample the PC. */
2885 if((retval = target_halt(target)) != ERROR_OK)
2887 free(samples);
2888 return retval;
2890 } else
2892 command_print(cmd_ctx, "Target not halted or running");
2893 retval=ERROR_OK;
2894 break;
2896 if (retval!=ERROR_OK)
2898 break;
2901 gettimeofday(&now, NULL);
2902 if ((numSamples>=maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
2904 command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
2905 if((retval = target_poll(target)) != ERROR_OK)
2907 free(samples);
2908 return retval;
2910 if (target->state == TARGET_HALTED)
2912 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2914 if((retval = target_poll(target)) != ERROR_OK)
2916 free(samples);
2917 return retval;
2919 writeGmon(samples, numSamples, args[1]);
2920 command_print(cmd_ctx, "Wrote %s", args[1]);
2921 break;
2924 free(samples);
2926 return ERROR_OK;
2929 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
2931 char *namebuf;
2932 Jim_Obj *nameObjPtr, *valObjPtr;
2933 int result;
2935 namebuf = alloc_printf("%s(%d)", varname, idx);
2936 if (!namebuf)
2937 return JIM_ERR;
2939 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
2940 valObjPtr = Jim_NewIntObj(interp, val);
2941 if (!nameObjPtr || !valObjPtr)
2943 free(namebuf);
2944 return JIM_ERR;
2947 Jim_IncrRefCount(nameObjPtr);
2948 Jim_IncrRefCount(valObjPtr);
2949 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
2950 Jim_DecrRefCount(interp, nameObjPtr);
2951 Jim_DecrRefCount(interp, valObjPtr);
2952 free(namebuf);
2953 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
2954 return result;
2957 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
2959 command_context_t *context;
2960 target_t *target;
2962 context = Jim_GetAssocData(interp, "context");
2963 if (context == NULL)
2965 LOG_ERROR("mem2array: no command context");
2966 return JIM_ERR;
2968 target = get_current_target(context);
2969 if (target == NULL)
2971 LOG_ERROR("mem2array: no current target");
2972 return JIM_ERR;
2975 return target_mem2array(interp, target, argc-1, argv+1);
2978 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
2980 long l;
2981 uint32_t width;
2982 int len;
2983 uint32_t addr;
2984 uint32_t count;
2985 uint32_t v;
2986 const char *varname;
2987 uint8_t buffer[4096];
2988 int n, e, retval;
2989 uint32_t i;
2991 /* argv[1] = name of array to receive the data
2992 * argv[2] = desired width
2993 * argv[3] = memory address
2994 * argv[4] = count of times to read
2996 if (argc != 4) {
2997 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
2998 return JIM_ERR;
3000 varname = Jim_GetString(argv[0], &len);
3001 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3003 e = Jim_GetLong(interp, argv[1], &l);
3004 width = l;
3005 if (e != JIM_OK) {
3006 return e;
3009 e = Jim_GetLong(interp, argv[2], &l);
3010 addr = l;
3011 if (e != JIM_OK) {
3012 return e;
3014 e = Jim_GetLong(interp, argv[3], &l);
3015 len = l;
3016 if (e != JIM_OK) {
3017 return e;
3019 switch (width) {
3020 case 8:
3021 width = 1;
3022 break;
3023 case 16:
3024 width = 2;
3025 break;
3026 case 32:
3027 width = 4;
3028 break;
3029 default:
3030 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3031 Jim_AppendStrings( interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL );
3032 return JIM_ERR;
3034 if (len == 0) {
3035 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3036 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3037 return JIM_ERR;
3039 if ((addr + (len * width)) < addr) {
3040 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3041 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3042 return JIM_ERR;
3044 /* absurd transfer size? */
3045 if (len > 65536) {
3046 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3047 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3048 return JIM_ERR;
3051 if ((width == 1) ||
3052 ((width == 2) && ((addr & 1) == 0)) ||
3053 ((width == 4) && ((addr & 3) == 0))) {
3054 /* all is well */
3055 } else {
3056 char buf[100];
3057 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3058 sprintf(buf, "mem2array address: 0x%08x is not aligned for %d byte reads", addr, width);
3059 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3060 return JIM_ERR;
3063 /* Transfer loop */
3065 /* index counter */
3066 n = 0;
3067 /* assume ok */
3068 e = JIM_OK;
3069 while (len) {
3070 /* Slurp... in buffer size chunks */
3072 count = len; /* in objects.. */
3073 if (count > (sizeof(buffer)/width)) {
3074 count = (sizeof(buffer)/width);
3077 retval = target_read_memory( target, addr, width, count, buffer );
3078 if (retval != ERROR_OK) {
3079 /* BOO !*/
3080 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed", addr, width, count);
3081 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3082 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3083 e = JIM_ERR;
3084 len = 0;
3085 } else {
3086 v = 0; /* shut up gcc */
3087 for (i = 0 ;i < count ;i++, n++) {
3088 switch (width) {
3089 case 4:
3090 v = target_buffer_get_u32(target, &buffer[i*width]);
3091 break;
3092 case 2:
3093 v = target_buffer_get_u16(target, &buffer[i*width]);
3094 break;
3095 case 1:
3096 v = buffer[i] & 0x0ff;
3097 break;
3099 new_int_array_element(interp, varname, n, v);
3101 len -= count;
3105 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3107 return JIM_OK;
3110 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3112 char *namebuf;
3113 Jim_Obj *nameObjPtr, *valObjPtr;
3114 int result;
3115 long l;
3117 namebuf = alloc_printf("%s(%d)", varname, idx);
3118 if (!namebuf)
3119 return JIM_ERR;
3121 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3122 if (!nameObjPtr)
3124 free(namebuf);
3125 return JIM_ERR;
3128 Jim_IncrRefCount(nameObjPtr);
3129 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3130 Jim_DecrRefCount(interp, nameObjPtr);
3131 free(namebuf);
3132 if (valObjPtr == NULL)
3133 return JIM_ERR;
3135 result = Jim_GetLong(interp, valObjPtr, &l);
3136 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3137 *val = l;
3138 return result;
3141 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3143 command_context_t *context;
3144 target_t *target;
3146 context = Jim_GetAssocData(interp, "context");
3147 if (context == NULL){
3148 LOG_ERROR("array2mem: no command context");
3149 return JIM_ERR;
3151 target = get_current_target(context);
3152 if (target == NULL){
3153 LOG_ERROR("array2mem: no current target");
3154 return JIM_ERR;
3157 return target_array2mem( interp,target, argc-1, argv+1 );
3160 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3162 long l;
3163 uint32_t width;
3164 int len;
3165 uint32_t addr;
3166 uint32_t count;
3167 uint32_t v;
3168 const char *varname;
3169 uint8_t buffer[4096];
3170 int n, e, retval;
3171 uint32_t i;
3173 /* argv[1] = name of array to get the data
3174 * argv[2] = desired width
3175 * argv[3] = memory address
3176 * argv[4] = count to write
3178 if (argc != 4) {
3179 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3180 return JIM_ERR;
3182 varname = Jim_GetString(argv[0], &len);
3183 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3185 e = Jim_GetLong(interp, argv[1], &l);
3186 width = l;
3187 if (e != JIM_OK) {
3188 return e;
3191 e = Jim_GetLong(interp, argv[2], &l);
3192 addr = l;
3193 if (e != JIM_OK) {
3194 return e;
3196 e = Jim_GetLong(interp, argv[3], &l);
3197 len = l;
3198 if (e != JIM_OK) {
3199 return e;
3201 switch (width) {
3202 case 8:
3203 width = 1;
3204 break;
3205 case 16:
3206 width = 2;
3207 break;
3208 case 32:
3209 width = 4;
3210 break;
3211 default:
3212 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3213 Jim_AppendStrings( interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL );
3214 return JIM_ERR;
3216 if (len == 0) {
3217 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3218 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3219 return JIM_ERR;
3221 if ((addr + (len * width)) < addr) {
3222 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3223 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3224 return JIM_ERR;
3226 /* absurd transfer size? */
3227 if (len > 65536) {
3228 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3229 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3230 return JIM_ERR;
3233 if ((width == 1) ||
3234 ((width == 2) && ((addr & 1) == 0)) ||
3235 ((width == 4) && ((addr & 3) == 0))) {
3236 /* all is well */
3237 } else {
3238 char buf[100];
3239 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3240 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads", addr, width);
3241 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3242 return JIM_ERR;
3245 /* Transfer loop */
3247 /* index counter */
3248 n = 0;
3249 /* assume ok */
3250 e = JIM_OK;
3251 while (len) {
3252 /* Slurp... in buffer size chunks */
3254 count = len; /* in objects.. */
3255 if (count > (sizeof(buffer)/width)) {
3256 count = (sizeof(buffer)/width);
3259 v = 0; /* shut up gcc */
3260 for (i = 0 ;i < count ;i++, n++) {
3261 get_int_array_element(interp, varname, n, &v);
3262 switch (width) {
3263 case 4:
3264 target_buffer_set_u32(target, &buffer[i*width], v);
3265 break;
3266 case 2:
3267 target_buffer_set_u16(target, &buffer[i*width], v);
3268 break;
3269 case 1:
3270 buffer[i] = v & 0x0ff;
3271 break;
3274 len -= count;
3276 retval = target_write_memory(target, addr, width, count, buffer);
3277 if (retval != ERROR_OK) {
3278 /* BOO !*/
3279 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed", addr, width, count);
3280 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3281 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3282 e = JIM_ERR;
3283 len = 0;
3287 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3289 return JIM_OK;
3292 void target_all_handle_event( enum target_event e )
3294 target_t *target;
3296 LOG_DEBUG( "**all*targets: event: %d, %s",
3298 Jim_Nvp_value2name_simple( nvp_target_event, e )->name );
3300 target = all_targets;
3301 while (target){
3302 target_handle_event( target, e );
3303 target = target->next;
3307 void target_handle_event( target_t *target, enum target_event e )
3309 target_event_action_t *teap;
3310 int done;
3312 teap = target->event_action;
3314 done = 0;
3315 while( teap ){
3316 if( teap->event == e ){
3317 done = 1;
3318 LOG_DEBUG( "target: (%d) %s (%s) event: %d (%s) action: %s\n",
3319 target->target_number,
3320 target->cmd_name,
3321 target_get_name(target),
3323 Jim_Nvp_value2name_simple( nvp_target_event, e )->name,
3324 Jim_GetString( teap->body, NULL ) );
3325 if (Jim_EvalObj( interp, teap->body )!=JIM_OK)
3327 Jim_PrintErrorMessage(interp);
3330 teap = teap->next;
3332 if( !done ){
3333 LOG_DEBUG( "event: %d %s - no action",
3335 Jim_Nvp_value2name_simple( nvp_target_event, e )->name );
3339 enum target_cfg_param {
3340 TCFG_TYPE,
3341 TCFG_EVENT,
3342 TCFG_WORK_AREA_VIRT,
3343 TCFG_WORK_AREA_PHYS,
3344 TCFG_WORK_AREA_SIZE,
3345 TCFG_WORK_AREA_BACKUP,
3346 TCFG_ENDIAN,
3347 TCFG_VARIANT,
3348 TCFG_CHAIN_POSITION,
3351 static Jim_Nvp nvp_config_opts[] = {
3352 { .name = "-type", .value = TCFG_TYPE },
3353 { .name = "-event", .value = TCFG_EVENT },
3354 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3355 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3356 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3357 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3358 { .name = "-endian" , .value = TCFG_ENDIAN },
3359 { .name = "-variant", .value = TCFG_VARIANT },
3360 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3362 { .name = NULL, .value = -1 }
3365 static int target_configure( Jim_GetOptInfo *goi, target_t *target )
3367 Jim_Nvp *n;
3368 Jim_Obj *o;
3369 jim_wide w;
3370 char *cp;
3371 int e;
3373 /* parse config or cget options ... */
3374 while( goi->argc > 0 ){
3375 Jim_SetEmptyResult( goi->interp );
3376 /* Jim_GetOpt_Debug( goi ); */
3378 if( target->type->target_jim_configure ){
3379 /* target defines a configure function */
3380 /* target gets first dibs on parameters */
3381 e = (*(target->type->target_jim_configure))( target, goi );
3382 if( e == JIM_OK ){
3383 /* more? */
3384 continue;
3386 if( e == JIM_ERR ){
3387 /* An error */
3388 return e;
3390 /* otherwise we 'continue' below */
3392 e = Jim_GetOpt_Nvp( goi, nvp_config_opts, &n );
3393 if( e != JIM_OK ){
3394 Jim_GetOpt_NvpUnknown( goi, nvp_config_opts, 0 );
3395 return e;
3397 switch( n->value ){
3398 case TCFG_TYPE:
3399 /* not setable */
3400 if( goi->isconfigure ){
3401 Jim_SetResult_sprintf( goi->interp, "not setable: %s", n->name );
3402 return JIM_ERR;
3403 } else {
3404 no_params:
3405 if( goi->argc != 0 ){
3406 Jim_WrongNumArgs( goi->interp, goi->argc, goi->argv, "NO PARAMS");
3407 return JIM_ERR;
3410 Jim_SetResultString( goi->interp, target_get_name(target), -1 );
3411 /* loop for more */
3412 break;
3413 case TCFG_EVENT:
3414 if( goi->argc == 0 ){
3415 Jim_WrongNumArgs( goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3416 return JIM_ERR;
3419 e = Jim_GetOpt_Nvp( goi, nvp_target_event, &n );
3420 if( e != JIM_OK ){
3421 Jim_GetOpt_NvpUnknown( goi, nvp_target_event, 1 );
3422 return e;
3425 if( goi->isconfigure ){
3426 if( goi->argc != 1 ){
3427 Jim_WrongNumArgs( goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3428 return JIM_ERR;
3430 } else {
3431 if( goi->argc != 0 ){
3432 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3433 return JIM_ERR;
3438 target_event_action_t *teap;
3440 teap = target->event_action;
3441 /* replace existing? */
3442 while( teap ){
3443 if( teap->event == (enum target_event)n->value ){
3444 break;
3446 teap = teap->next;
3449 if( goi->isconfigure ){
3450 if( teap == NULL ){
3451 /* create new */
3452 teap = calloc( 1, sizeof(*teap) );
3454 teap->event = n->value;
3455 Jim_GetOpt_Obj( goi, &o );
3456 if( teap->body ){
3457 Jim_DecrRefCount( interp, teap->body );
3459 teap->body = Jim_DuplicateObj( goi->interp, o );
3461 * FIXME:
3462 * Tcl/TK - "tk events" have a nice feature.
3463 * See the "BIND" command.
3464 * We should support that here.
3465 * You can specify %X and %Y in the event code.
3466 * The idea is: %T - target name.
3467 * The idea is: %N - target number
3468 * The idea is: %E - event name.
3470 Jim_IncrRefCount( teap->body );
3472 /* add to head of event list */
3473 teap->next = target->event_action;
3474 target->event_action = teap;
3475 Jim_SetEmptyResult(goi->interp);
3476 } else {
3477 /* get */
3478 if( teap == NULL ){
3479 Jim_SetEmptyResult( goi->interp );
3480 } else {
3481 Jim_SetResult( goi->interp, Jim_DuplicateObj( goi->interp, teap->body ) );
3485 /* loop for more */
3486 break;
3488 case TCFG_WORK_AREA_VIRT:
3489 if( goi->isconfigure ){
3490 target_free_all_working_areas(target);
3491 e = Jim_GetOpt_Wide( goi, &w );
3492 if( e != JIM_OK ){
3493 return e;
3495 target->working_area_virt = w;
3496 } else {
3497 if( goi->argc != 0 ){
3498 goto no_params;
3501 Jim_SetResult( interp, Jim_NewIntObj( goi->interp, target->working_area_virt ) );
3502 /* loop for more */
3503 break;
3505 case TCFG_WORK_AREA_PHYS:
3506 if( goi->isconfigure ){
3507 target_free_all_working_areas(target);
3508 e = Jim_GetOpt_Wide( goi, &w );
3509 if( e != JIM_OK ){
3510 return e;
3512 target->working_area_phys = w;
3513 } else {
3514 if( goi->argc != 0 ){
3515 goto no_params;
3518 Jim_SetResult( interp, Jim_NewIntObj( goi->interp, target->working_area_phys ) );
3519 /* loop for more */
3520 break;
3522 case TCFG_WORK_AREA_SIZE:
3523 if( goi->isconfigure ){
3524 target_free_all_working_areas(target);
3525 e = Jim_GetOpt_Wide( goi, &w );
3526 if( e != JIM_OK ){
3527 return e;
3529 target->working_area_size = w;
3530 } else {
3531 if( goi->argc != 0 ){
3532 goto no_params;
3535 Jim_SetResult( interp, Jim_NewIntObj( goi->interp, target->working_area_size ) );
3536 /* loop for more */
3537 break;
3539 case TCFG_WORK_AREA_BACKUP:
3540 if( goi->isconfigure ){
3541 target_free_all_working_areas(target);
3542 e = Jim_GetOpt_Wide( goi, &w );
3543 if( e != JIM_OK ){
3544 return e;
3546 /* make this exactly 1 or 0 */
3547 target->backup_working_area = (!!w);
3548 } else {
3549 if( goi->argc != 0 ){
3550 goto no_params;
3553 Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3554 /* loop for more e*/
3555 break;
3557 case TCFG_ENDIAN:
3558 if( goi->isconfigure ){
3559 e = Jim_GetOpt_Nvp( goi, nvp_target_endian, &n );
3560 if( e != JIM_OK ){
3561 Jim_GetOpt_NvpUnknown( goi, nvp_target_endian, 1 );
3562 return e;
3564 target->endianness = n->value;
3565 } else {
3566 if( goi->argc != 0 ){
3567 goto no_params;
3570 n = Jim_Nvp_value2name_simple( nvp_target_endian, target->endianness );
3571 if( n->name == NULL ){
3572 target->endianness = TARGET_LITTLE_ENDIAN;
3573 n = Jim_Nvp_value2name_simple( nvp_target_endian, target->endianness );
3575 Jim_SetResultString( goi->interp, n->name, -1 );
3576 /* loop for more */
3577 break;
3579 case TCFG_VARIANT:
3580 if( goi->isconfigure ){
3581 if( goi->argc < 1 ){
3582 Jim_SetResult_sprintf( goi->interp,
3583 "%s ?STRING?",
3584 n->name );
3585 return JIM_ERR;
3587 if( target->variant ){
3588 free((void *)(target->variant));
3590 e = Jim_GetOpt_String( goi, &cp, NULL );
3591 target->variant = strdup(cp);
3592 } else {
3593 if( goi->argc != 0 ){
3594 goto no_params;
3597 Jim_SetResultString( goi->interp, target->variant,-1 );
3598 /* loop for more */
3599 break;
3600 case TCFG_CHAIN_POSITION:
3601 if( goi->isconfigure ){
3602 Jim_Obj *o;
3603 jtag_tap_t *tap;
3604 target_free_all_working_areas(target);
3605 e = Jim_GetOpt_Obj( goi, &o );
3606 if( e != JIM_OK ){
3607 return e;
3609 tap = jtag_tap_by_jim_obj( goi->interp, o );
3610 if( tap == NULL ){
3611 return JIM_ERR;
3613 /* make this exactly 1 or 0 */
3614 target->tap = tap;
3615 } else {
3616 if( goi->argc != 0 ){
3617 goto no_params;
3620 Jim_SetResultString( interp, target->tap->dotted_name, -1 );
3621 /* loop for more e*/
3622 break;
3624 } /* while( goi->argc ) */
3627 /* done - we return */
3628 return JIM_OK;
3631 /** this is the 'tcl' handler for the target specific command */
3632 static int tcl_target_func( Jim_Interp *interp, int argc, Jim_Obj *const *argv )
3634 Jim_GetOptInfo goi;
3635 jim_wide a,b,c;
3636 int x,y,z;
3637 uint8_t target_buf[32];
3638 Jim_Nvp *n;
3639 target_t *target;
3640 struct command_context_s *cmd_ctx;
3641 int e;
3643 enum {
3644 TS_CMD_CONFIGURE,
3645 TS_CMD_CGET,
3647 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3648 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3649 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3650 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3651 TS_CMD_EXAMINE,
3652 TS_CMD_POLL,
3653 TS_CMD_RESET,
3654 TS_CMD_HALT,
3655 TS_CMD_WAITSTATE,
3656 TS_CMD_EVENTLIST,
3657 TS_CMD_CURSTATE,
3658 TS_CMD_INVOKE_EVENT,
3661 static const Jim_Nvp target_options[] = {
3662 { .name = "configure", .value = TS_CMD_CONFIGURE },
3663 { .name = "cget", .value = TS_CMD_CGET },
3664 { .name = "mww", .value = TS_CMD_MWW },
3665 { .name = "mwh", .value = TS_CMD_MWH },
3666 { .name = "mwb", .value = TS_CMD_MWB },
3667 { .name = "mdw", .value = TS_CMD_MDW },
3668 { .name = "mdh", .value = TS_CMD_MDH },
3669 { .name = "mdb", .value = TS_CMD_MDB },
3670 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3671 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3672 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3673 { .name = "curstate", .value = TS_CMD_CURSTATE },
3675 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3676 { .name = "arp_poll", .value = TS_CMD_POLL },
3677 { .name = "arp_reset", .value = TS_CMD_RESET },
3678 { .name = "arp_halt", .value = TS_CMD_HALT },
3679 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3680 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3682 { .name = NULL, .value = -1 },
3685 /* go past the "command" */
3686 Jim_GetOpt_Setup( &goi, interp, argc-1, argv+1 );
3688 target = Jim_CmdPrivData( goi.interp );
3689 cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3691 /* commands here are in an NVP table */
3692 e = Jim_GetOpt_Nvp( &goi, target_options, &n );
3693 if( e != JIM_OK ){
3694 Jim_GetOpt_NvpUnknown( &goi, target_options, 0 );
3695 return e;
3697 /* Assume blank result */
3698 Jim_SetEmptyResult( goi.interp );
3700 switch( n->value ){
3701 case TS_CMD_CONFIGURE:
3702 if( goi.argc < 2 ){
3703 Jim_WrongNumArgs( goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3704 return JIM_ERR;
3706 goi.isconfigure = 1;
3707 return target_configure( &goi, target );
3708 case TS_CMD_CGET:
3709 // some things take params
3710 if( goi.argc < 1 ){
3711 Jim_WrongNumArgs( goi.interp, 0, goi.argv, "missing: ?-option?");
3712 return JIM_ERR;
3714 goi.isconfigure = 0;
3715 return target_configure( &goi, target );
3716 break;
3717 case TS_CMD_MWW:
3718 case TS_CMD_MWH:
3719 case TS_CMD_MWB:
3720 /* argv[0] = cmd
3721 * argv[1] = address
3722 * argv[2] = data
3723 * argv[3] = optional count.
3726 if( (goi.argc == 2) || (goi.argc == 3) ){
3727 /* all is well */
3728 } else {
3729 mwx_error:
3730 Jim_SetResult_sprintf( goi.interp, "expected: %s ADDR DATA [COUNT]", n->name );
3731 return JIM_ERR;
3734 e = Jim_GetOpt_Wide( &goi, &a );
3735 if( e != JIM_OK ){
3736 goto mwx_error;
3739 e = Jim_GetOpt_Wide( &goi, &b );
3740 if( e != JIM_OK ){
3741 goto mwx_error;
3743 if (goi.argc == 3) {
3744 e = Jim_GetOpt_Wide( &goi, &c );
3745 if( e != JIM_OK ){
3746 goto mwx_error;
3748 } else {
3749 c = 1;
3752 switch( n->value ){
3753 case TS_CMD_MWW:
3754 target_buffer_set_u32( target, target_buf, b );
3755 b = 4;
3756 break;
3757 case TS_CMD_MWH:
3758 target_buffer_set_u16( target, target_buf, b );
3759 b = 2;
3760 break;
3761 case TS_CMD_MWB:
3762 target_buffer_set_u8( target, target_buf, b );
3763 b = 1;
3764 break;
3766 for( x = 0 ; x < c ; x++ ){
3767 e = target_write_memory( target, a, b, 1, target_buf );
3768 if( e != ERROR_OK ){
3769 Jim_SetResult_sprintf( interp, "Error writing @ 0x%08x: %d\n", (int)(a), e );
3770 return JIM_ERR;
3772 /* b = width */
3773 a = a + b;
3775 return JIM_OK;
3776 break;
3778 /* display */
3779 case TS_CMD_MDW:
3780 case TS_CMD_MDH:
3781 case TS_CMD_MDB:
3782 /* argv[0] = command
3783 * argv[1] = address
3784 * argv[2] = optional count
3786 if( (goi.argc == 2) || (goi.argc == 3) ){
3787 Jim_SetResult_sprintf( goi.interp, "expected: %s ADDR [COUNT]", n->name );
3788 return JIM_ERR;
3790 e = Jim_GetOpt_Wide( &goi, &a );
3791 if( e != JIM_OK ){
3792 return JIM_ERR;
3794 if( goi.argc ){
3795 e = Jim_GetOpt_Wide( &goi, &c );
3796 if( e != JIM_OK ){
3797 return JIM_ERR;
3799 } else {
3800 c = 1;
3802 b = 1; /* shut up gcc */
3803 switch( n->value ){
3804 case TS_CMD_MDW:
3805 b = 4;
3806 break;
3807 case TS_CMD_MDH:
3808 b = 2;
3809 break;
3810 case TS_CMD_MDB:
3811 b = 1;
3812 break;
3815 /* convert to "bytes" */
3816 c = c * b;
3817 /* count is now in 'BYTES' */
3818 while( c > 0 ){
3819 y = c;
3820 if( y > 16 ){
3821 y = 16;
3823 e = target_read_memory( target, a, b, y / b, target_buf );
3824 if( e != ERROR_OK ){
3825 Jim_SetResult_sprintf( interp, "error reading target @ 0x%08lx", (int)(a) );
3826 return JIM_ERR;
3829 Jim_fprintf( interp, interp->cookie_stdout, "0x%08x ", (int)(a) );
3830 switch( b ){
3831 case 4:
3832 for( x = 0 ; (x < 16) && (x < y) ; x += 4 ){
3833 z = target_buffer_get_u32( target, &(target_buf[ x * 4 ]) );
3834 Jim_fprintf( interp, interp->cookie_stdout, "%08x ", (int)(z) );
3836 for( ; (x < 16) ; x += 4 ){
3837 Jim_fprintf( interp, interp->cookie_stdout, " " );
3839 break;
3840 case 2:
3841 for( x = 0 ; (x < 16) && (x < y) ; x += 2 ){
3842 z = target_buffer_get_u16( target, &(target_buf[ x * 2 ]) );
3843 Jim_fprintf( interp, interp->cookie_stdout, "%04x ", (int)(z) );
3845 for( ; (x < 16) ; x += 2 ){
3846 Jim_fprintf( interp, interp->cookie_stdout, " " );
3848 break;
3849 case 1:
3850 default:
3851 for( x = 0 ; (x < 16) && (x < y) ; x += 1 ){
3852 z = target_buffer_get_u8( target, &(target_buf[ x * 4 ]) );
3853 Jim_fprintf( interp, interp->cookie_stdout, "%02x ", (int)(z) );
3855 for( ; (x < 16) ; x += 1 ){
3856 Jim_fprintf( interp, interp->cookie_stdout, " " );
3858 break;
3860 /* ascii-ify the bytes */
3861 for( x = 0 ; x < y ; x++ ){
3862 if( (target_buf[x] >= 0x20) &&
3863 (target_buf[x] <= 0x7e) ){
3864 /* good */
3865 } else {
3866 /* smack it */
3867 target_buf[x] = '.';
3870 /* space pad */
3871 while( x < 16 ){
3872 target_buf[x] = ' ';
3873 x++;
3875 /* terminate */
3876 target_buf[16] = 0;
3877 /* print - with a newline */
3878 Jim_fprintf( interp, interp->cookie_stdout, "%s\n", target_buf );
3879 /* NEXT... */
3880 c -= 16;
3881 a += 16;
3883 return JIM_OK;
3884 case TS_CMD_MEM2ARRAY:
3885 return target_mem2array( goi.interp, target, goi.argc, goi.argv );
3886 break;
3887 case TS_CMD_ARRAY2MEM:
3888 return target_array2mem( goi.interp, target, goi.argc, goi.argv );
3889 break;
3890 case TS_CMD_EXAMINE:
3891 if( goi.argc ){
3892 Jim_WrongNumArgs( goi.interp, 2, argv, "[no parameters]");
3893 return JIM_ERR;
3895 if (!target->tap->enabled)
3896 goto err_tap_disabled;
3897 e = target->type->examine( target );
3898 if( e != ERROR_OK ){
3899 Jim_SetResult_sprintf( interp, "examine-fails: %d", e );
3900 return JIM_ERR;
3902 return JIM_OK;
3903 case TS_CMD_POLL:
3904 if( goi.argc ){
3905 Jim_WrongNumArgs( goi.interp, 2, argv, "[no parameters]");
3906 return JIM_ERR;
3908 if (!target->tap->enabled)
3909 goto err_tap_disabled;
3910 if( !(target_was_examined(target)) ){
3911 e = ERROR_TARGET_NOT_EXAMINED;
3912 } else {
3913 e = target->type->poll( target );
3915 if( e != ERROR_OK ){
3916 Jim_SetResult_sprintf( interp, "poll-fails: %d", e );
3917 return JIM_ERR;
3918 } else {
3919 return JIM_OK;
3921 break;
3922 case TS_CMD_RESET:
3923 if( goi.argc != 2 ){
3924 Jim_WrongNumArgs( interp, 2, argv, "t|f|assert|deassert BOOL");
3925 return JIM_ERR;
3927 e = Jim_GetOpt_Nvp( &goi, nvp_assert, &n );
3928 if( e != JIM_OK ){
3929 Jim_GetOpt_NvpUnknown( &goi, nvp_assert, 1 );
3930 return e;
3932 /* the halt or not param */
3933 e = Jim_GetOpt_Wide( &goi, &a);
3934 if( e != JIM_OK ){
3935 return e;
3937 if (!target->tap->enabled)
3938 goto err_tap_disabled;
3939 /* determine if we should halt or not. */
3940 target->reset_halt = !!a;
3941 /* When this happens - all workareas are invalid. */
3942 target_free_all_working_areas_restore(target, 0);
3944 /* do the assert */
3945 if( n->value == NVP_ASSERT ){
3946 target->type->assert_reset( target );
3947 } else {
3948 target->type->deassert_reset( target );
3950 return JIM_OK;
3951 case TS_CMD_HALT:
3952 if( goi.argc ){
3953 Jim_WrongNumArgs( goi.interp, 0, argv, "halt [no parameters]");
3954 return JIM_ERR;
3956 if (!target->tap->enabled)
3957 goto err_tap_disabled;
3958 target->type->halt( target );
3959 return JIM_OK;
3960 case TS_CMD_WAITSTATE:
3961 /* params: <name> statename timeoutmsecs */
3962 if( goi.argc != 2 ){
3963 Jim_SetResult_sprintf( goi.interp, "%s STATENAME TIMEOUTMSECS", n->name );
3964 return JIM_ERR;
3966 e = Jim_GetOpt_Nvp( &goi, nvp_target_state, &n );
3967 if( e != JIM_OK ){
3968 Jim_GetOpt_NvpUnknown( &goi, nvp_target_state,1 );
3969 return e;
3971 e = Jim_GetOpt_Wide( &goi, &a );
3972 if( e != JIM_OK ){
3973 return e;
3975 if (!target->tap->enabled)
3976 goto err_tap_disabled;
3977 e = target_wait_state( target, n->value, a );
3978 if( e != ERROR_OK ){
3979 Jim_SetResult_sprintf( goi.interp,
3980 "target: %s wait %s fails (%d) %s",
3981 target->cmd_name,
3982 n->name,
3983 e, target_strerror_safe(e) );
3984 return JIM_ERR;
3985 } else {
3986 return JIM_OK;
3988 case TS_CMD_EVENTLIST:
3989 /* List for human, Events defined for this target.
3990 * scripts/programs should use 'name cget -event NAME'
3993 target_event_action_t *teap;
3994 teap = target->event_action;
3995 command_print( cmd_ctx, "Event actions for target (%d) %s\n",
3996 target->target_number,
3997 target->cmd_name );
3998 command_print( cmd_ctx, "%-25s | Body", "Event");
3999 command_print( cmd_ctx, "------------------------- | ----------------------------------------");
4000 while( teap ){
4001 command_print( cmd_ctx,
4002 "%-25s | %s",
4003 Jim_Nvp_value2name_simple( nvp_target_event, teap->event )->name,
4004 Jim_GetString( teap->body, NULL ) );
4005 teap = teap->next;
4007 command_print( cmd_ctx, "***END***");
4008 return JIM_OK;
4010 case TS_CMD_CURSTATE:
4011 if( goi.argc != 0 ){
4012 Jim_WrongNumArgs( goi.interp, 0, argv, "[no parameters]");
4013 return JIM_ERR;
4015 Jim_SetResultString( goi.interp,
4016 Jim_Nvp_value2name_simple(nvp_target_state,target->state)->name,-1);
4017 return JIM_OK;
4018 case TS_CMD_INVOKE_EVENT:
4019 if( goi.argc != 1 ){
4020 Jim_SetResult_sprintf( goi.interp, "%s ?EVENTNAME?",n->name);
4021 return JIM_ERR;
4023 e = Jim_GetOpt_Nvp( &goi, nvp_target_event, &n );
4024 if( e != JIM_OK ){
4025 Jim_GetOpt_NvpUnknown( &goi, nvp_target_event, 1 );
4026 return e;
4028 target_handle_event( target, n->value );
4029 return JIM_OK;
4031 return JIM_ERR;
4033 err_tap_disabled:
4034 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4035 return JIM_ERR;
4038 static int target_create( Jim_GetOptInfo *goi )
4040 Jim_Obj *new_cmd;
4041 Jim_Cmd *cmd;
4042 const char *cp;
4043 char *cp2;
4044 int e;
4045 int x;
4046 target_t *target;
4047 struct command_context_s *cmd_ctx;
4049 cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4050 if( goi->argc < 3 ){
4051 Jim_WrongNumArgs( goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4052 return JIM_ERR;
4055 /* COMMAND */
4056 Jim_GetOpt_Obj( goi, &new_cmd );
4057 /* does this command exist? */
4058 cmd = Jim_GetCommand( goi->interp, new_cmd, JIM_ERRMSG );
4059 if( cmd ){
4060 cp = Jim_GetString( new_cmd, NULL );
4061 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4062 return JIM_ERR;
4065 /* TYPE */
4066 e = Jim_GetOpt_String( goi, &cp2, NULL );
4067 cp = cp2;
4068 /* now does target type exist */
4069 for( x = 0 ; target_types[x] ; x++ ){
4070 if( 0 == strcmp( cp, target_types[x]->name ) ){
4071 /* found */
4072 break;
4075 if( target_types[x] == NULL ){
4076 Jim_SetResult_sprintf( goi->interp, "Unknown target type %s, try one of ", cp );
4077 for( x = 0 ; target_types[x] ; x++ ){
4078 if( target_types[x+1] ){
4079 Jim_AppendStrings( goi->interp,
4080 Jim_GetResult(goi->interp),
4081 target_types[x]->name,
4082 ", ", NULL);
4083 } else {
4084 Jim_AppendStrings( goi->interp,
4085 Jim_GetResult(goi->interp),
4086 " or ",
4087 target_types[x]->name,NULL );
4090 return JIM_ERR;
4093 /* Create it */
4094 target = calloc(1,sizeof(target_t));
4095 /* set target number */
4096 target->target_number = new_target_number();
4098 /* allocate memory for each unique target type */
4099 target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4101 memcpy( target->type, target_types[x], sizeof(target_type_t));
4103 /* will be set by "-endian" */
4104 target->endianness = TARGET_ENDIAN_UNKNOWN;
4106 target->working_area = 0x0;
4107 target->working_area_size = 0x0;
4108 target->working_areas = NULL;
4109 target->backup_working_area = 0;
4111 target->state = TARGET_UNKNOWN;
4112 target->debug_reason = DBG_REASON_UNDEFINED;
4113 target->reg_cache = NULL;
4114 target->breakpoints = NULL;
4115 target->watchpoints = NULL;
4116 target->next = NULL;
4117 target->arch_info = NULL;
4119 target->display = 1;
4121 /* initialize trace information */
4122 target->trace_info = malloc(sizeof(trace_t));
4123 target->trace_info->num_trace_points = 0;
4124 target->trace_info->trace_points_size = 0;
4125 target->trace_info->trace_points = NULL;
4126 target->trace_info->trace_history_size = 0;
4127 target->trace_info->trace_history = NULL;
4128 target->trace_info->trace_history_pos = 0;
4129 target->trace_info->trace_history_overflowed = 0;
4131 target->dbgmsg = NULL;
4132 target->dbg_msg_enabled = 0;
4134 target->endianness = TARGET_ENDIAN_UNKNOWN;
4136 /* Do the rest as "configure" options */
4137 goi->isconfigure = 1;
4138 e = target_configure( goi, target);
4140 if (target->tap == NULL)
4142 Jim_SetResultString( interp, "-chain-position required when creating target", -1);
4143 e=JIM_ERR;
4146 if( e != JIM_OK ){
4147 free( target->type );
4148 free( target );
4149 return e;
4152 if( target->endianness == TARGET_ENDIAN_UNKNOWN ){
4153 /* default endian to little if not specified */
4154 target->endianness = TARGET_LITTLE_ENDIAN;
4157 /* incase variant is not set */
4158 if (!target->variant)
4159 target->variant = strdup("");
4161 /* create the target specific commands */
4162 if( target->type->register_commands ){
4163 (*(target->type->register_commands))( cmd_ctx );
4165 if( target->type->target_create ){
4166 (*(target->type->target_create))( target, goi->interp );
4169 /* append to end of list */
4171 target_t **tpp;
4172 tpp = &(all_targets);
4173 while( *tpp ){
4174 tpp = &( (*tpp)->next );
4176 *tpp = target;
4179 cp = Jim_GetString( new_cmd, NULL );
4180 target->cmd_name = strdup(cp);
4182 /* now - create the new target name command */
4183 e = Jim_CreateCommand( goi->interp,
4184 /* name */
4186 tcl_target_func, /* C function */
4187 target, /* private data */
4188 NULL ); /* no del proc */
4190 return e;
4193 static int jim_target( Jim_Interp *interp, int argc, Jim_Obj *const *argv )
4195 int x,r,e;
4196 jim_wide w;
4197 struct command_context_s *cmd_ctx;
4198 target_t *target;
4199 Jim_GetOptInfo goi;
4200 enum tcmd {
4201 /* TG = target generic */
4202 TG_CMD_CREATE,
4203 TG_CMD_TYPES,
4204 TG_CMD_NAMES,
4205 TG_CMD_CURRENT,
4206 TG_CMD_NUMBER,
4207 TG_CMD_COUNT,
4209 const char *target_cmds[] = {
4210 "create", "types", "names", "current", "number",
4211 "count",
4212 NULL /* terminate */
4215 LOG_DEBUG("Target command params:");
4216 LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4218 cmd_ctx = Jim_GetAssocData( interp, "context" );
4220 Jim_GetOpt_Setup( &goi, interp, argc-1, argv+1 );
4222 if( goi.argc == 0 ){
4223 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4224 return JIM_ERR;
4227 /* Jim_GetOpt_Debug( &goi ); */
4228 r = Jim_GetOpt_Enum( &goi, target_cmds, &x );
4229 if( r != JIM_OK ){
4230 return r;
4233 switch(x){
4234 default:
4235 Jim_Panic(goi.interp,"Why am I here?");
4236 return JIM_ERR;
4237 case TG_CMD_CURRENT:
4238 if( goi.argc != 0 ){
4239 Jim_WrongNumArgs( goi.interp, 1, goi.argv, "Too many parameters");
4240 return JIM_ERR;
4242 Jim_SetResultString( goi.interp, get_current_target( cmd_ctx )->cmd_name, -1 );
4243 return JIM_OK;
4244 case TG_CMD_TYPES:
4245 if( goi.argc != 0 ){
4246 Jim_WrongNumArgs( goi.interp, 1, goi.argv, "Too many parameters" );
4247 return JIM_ERR;
4249 Jim_SetResult( goi.interp, Jim_NewListObj( goi.interp, NULL, 0 ) );
4250 for( x = 0 ; target_types[x] ; x++ ){
4251 Jim_ListAppendElement( goi.interp,
4252 Jim_GetResult(goi.interp),
4253 Jim_NewStringObj( goi.interp, target_types[x]->name, -1 ) );
4255 return JIM_OK;
4256 case TG_CMD_NAMES:
4257 if( goi.argc != 0 ){
4258 Jim_WrongNumArgs( goi.interp, 1, goi.argv, "Too many parameters" );
4259 return JIM_ERR;
4261 Jim_SetResult( goi.interp, Jim_NewListObj( goi.interp, NULL, 0 ) );
4262 target = all_targets;
4263 while( target ){
4264 Jim_ListAppendElement( goi.interp,
4265 Jim_GetResult(goi.interp),
4266 Jim_NewStringObj( goi.interp, target->cmd_name, -1 ) );
4267 target = target->next;
4269 return JIM_OK;
4270 case TG_CMD_CREATE:
4271 if( goi.argc < 3 ){
4272 Jim_WrongNumArgs( goi.interp, goi.argc, goi.argv, "?name ... config options ...");
4273 return JIM_ERR;
4275 return target_create( &goi );
4276 break;
4277 case TG_CMD_NUMBER:
4278 if( goi.argc != 1 ){
4279 Jim_SetResult_sprintf( goi.interp, "expected: target number ?NUMBER?");
4280 return JIM_ERR;
4282 e = Jim_GetOpt_Wide( &goi, &w );
4283 if( e != JIM_OK ){
4284 return JIM_ERR;
4287 target_t *t;
4288 t = get_target_by_num(w);
4289 if( t == NULL ){
4290 Jim_SetResult_sprintf( goi.interp,"Target: number %d does not exist", (int)(w));
4291 return JIM_ERR;
4293 Jim_SetResultString( goi.interp, t->cmd_name, -1 );
4294 return JIM_OK;
4296 case TG_CMD_COUNT:
4297 if( goi.argc != 0 ){
4298 Jim_WrongNumArgs( goi.interp, 0, goi.argv, "<no parameters>");
4299 return JIM_ERR;
4301 Jim_SetResult( goi.interp,
4302 Jim_NewIntObj( goi.interp, max_target_number()));
4303 return JIM_OK;
4306 return JIM_ERR;
4310 struct FastLoad
4312 uint32_t address;
4313 uint8_t *data;
4314 int length;
4318 static int fastload_num;
4319 static struct FastLoad *fastload;
4321 static void free_fastload(void)
4323 if (fastload!=NULL)
4325 int i;
4326 for (i=0; i<fastload_num; i++)
4328 if (fastload[i].data)
4329 free(fastload[i].data);
4331 free(fastload);
4332 fastload=NULL;
4339 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4341 uint8_t *buffer;
4342 uint32_t buf_cnt;
4343 uint32_t image_size;
4344 uint32_t min_address=0;
4345 uint32_t max_address=0xffffffff;
4346 int i;
4348 image_t image;
4350 duration_t duration;
4351 char *duration_text;
4353 int retval = parse_load_image_command_args(args, argc,
4354 &image, &min_address, &max_address);
4355 if (ERROR_OK != retval)
4356 return retval;
4358 duration_start_measure(&duration);
4360 if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4362 return ERROR_OK;
4365 image_size = 0x0;
4366 retval = ERROR_OK;
4367 fastload_num=image.num_sections;
4368 fastload=(struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4369 if (fastload==NULL)
4371 image_close(&image);
4372 return ERROR_FAIL;
4374 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4375 for (i = 0; i < image.num_sections; i++)
4377 buffer = malloc(image.sections[i].size);
4378 if (buffer == NULL)
4380 command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
4381 break;
4384 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4386 free(buffer);
4387 break;
4390 uint32_t offset=0;
4391 uint32_t length=buf_cnt;
4394 /* DANGER!!! beware of unsigned comparision here!!! */
4396 if ((image.sections[i].base_address+buf_cnt>=min_address)&&
4397 (image.sections[i].base_address<max_address))
4399 if (image.sections[i].base_address<min_address)
4401 /* clip addresses below */
4402 offset+=min_address-image.sections[i].base_address;
4403 length-=offset;
4406 if (image.sections[i].base_address+buf_cnt>max_address)
4408 length-=(image.sections[i].base_address+buf_cnt)-max_address;
4411 fastload[i].address=image.sections[i].base_address+offset;
4412 fastload[i].data=malloc(length);
4413 if (fastload[i].data==NULL)
4415 free(buffer);
4416 break;
4418 memcpy(fastload[i].data, buffer+offset, length);
4419 fastload[i].length=length;
4421 image_size += length;
4422 command_print(cmd_ctx, "%u byte written at address 0x%8.8x", length, image.sections[i].base_address+offset);
4425 free(buffer);
4428 duration_stop_measure(&duration, &duration_text);
4429 if (retval==ERROR_OK)
4431 command_print(cmd_ctx, "Loaded %u bytes in %s", image_size, duration_text);
4432 command_print(cmd_ctx, "NB!!! image has not been loaded to target, issue a subsequent 'fast_load' to do so.");
4434 free(duration_text);
4436 image_close(&image);
4438 if (retval!=ERROR_OK)
4440 free_fastload();
4443 return retval;
4446 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4448 if (argc>0)
4449 return ERROR_COMMAND_SYNTAX_ERROR;
4450 if (fastload==NULL)
4452 LOG_ERROR("No image in memory");
4453 return ERROR_FAIL;
4455 int i;
4456 int ms=timeval_ms();
4457 int size=0;
4458 int retval=ERROR_OK;
4459 for (i=0; i<fastload_num;i++)
4461 target_t *target = get_current_target(cmd_ctx);
4462 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x", fastload[i].address, fastload[i].length);
4463 if (retval==ERROR_OK)
4465 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4467 size+=fastload[i].length;
4469 int after=timeval_ms();
4470 command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4471 return retval;