target: allow targets to override memory alignment
[openocd/openocdswd.git] / src / target / target.c
blob13d358d7c1a0fd9b5ca3faf7472689a22775da9a
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Ø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 <helper/time_support.h>
37 #include <jtag/jtag.h>
38 #include <flash/nor/core.h>
40 #include "target.h"
41 #include "target_type.h"
42 #include "target_request.h"
43 #include "breakpoints.h"
44 #include "register.h"
45 #include "trace.h"
46 #include "image.h"
49 static int target_read_buffer_default(struct target *target, uint32_t address,
50 uint32_t size, uint8_t *buffer);
51 static int target_write_buffer_default(struct target *target, uint32_t address,
52 uint32_t size, uint8_t *buffer);
53 static int target_array2mem(Jim_Interp *interp, struct target *target,
54 int argc, Jim_Obj *const *argv);
55 static int target_mem2array(Jim_Interp *interp, struct target *target,
56 int argc, Jim_Obj *const *argv);
57 static int target_register_user_commands(struct command_context *cmd_ctx);
59 /* targets */
60 extern struct target_type arm7tdmi_target;
61 extern struct target_type arm720t_target;
62 extern struct target_type arm9tdmi_target;
63 extern struct target_type arm920t_target;
64 extern struct target_type arm966e_target;
65 extern struct target_type arm946e_target;
66 extern struct target_type arm926ejs_target;
67 extern struct target_type fa526_target;
68 extern struct target_type feroceon_target;
69 extern struct target_type dragonite_target;
70 extern struct target_type xscale_target;
71 extern struct target_type cortexm3_target;
72 extern struct target_type cortexa8_target;
73 extern struct target_type cortexa9_target;
74 extern struct target_type arm11_target;
75 extern struct target_type mips_m4k_target;
76 extern struct target_type avr_target;
77 extern struct target_type dsp563xx_target;
78 extern struct target_type testee_target;
79 extern struct target_type avr32_ap7k_target;
81 static struct target_type *target_types[] =
83 &arm7tdmi_target,
84 &arm9tdmi_target,
85 &arm920t_target,
86 &arm720t_target,
87 &arm966e_target,
88 &arm946e_target,
89 &arm926ejs_target,
90 &fa526_target,
91 &feroceon_target,
92 &dragonite_target,
93 &xscale_target,
94 &cortexm3_target,
95 &cortexa8_target,
96 &cortexa9_target,
97 &arm11_target,
98 &mips_m4k_target,
99 &avr_target,
100 &dsp563xx_target,
101 &testee_target,
102 &avr32_ap7k_target,
103 NULL,
106 struct target *all_targets = NULL;
107 static struct target_event_callback *target_event_callbacks = NULL;
108 static struct target_timer_callback *target_timer_callbacks = NULL;
109 static const int polling_interval = 100;
111 static const Jim_Nvp nvp_assert[] = {
112 { .name = "assert", NVP_ASSERT },
113 { .name = "deassert", NVP_DEASSERT },
114 { .name = "T", NVP_ASSERT },
115 { .name = "F", NVP_DEASSERT },
116 { .name = "t", NVP_ASSERT },
117 { .name = "f", NVP_DEASSERT },
118 { .name = NULL, .value = -1 }
121 static const Jim_Nvp nvp_error_target[] = {
122 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
123 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
124 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
125 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
126 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
127 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
128 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
129 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
130 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
131 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
132 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
133 { .value = -1, .name = NULL }
136 static const char *target_strerror_safe(int err)
138 const Jim_Nvp *n;
140 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
141 if (n->name == NULL) {
142 return "unknown";
143 } else {
144 return n->name;
148 static const Jim_Nvp nvp_target_event[] = {
149 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
150 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
152 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
153 { .value = TARGET_EVENT_HALTED, .name = "halted" },
154 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
155 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
156 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
158 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
159 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
161 /* historical name */
163 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
165 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
166 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
167 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
168 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
169 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
170 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
171 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
172 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
173 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
174 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
175 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
177 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
178 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
180 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
181 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
183 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
184 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
186 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
187 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
189 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
190 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
192 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
193 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
194 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
196 { .name = NULL, .value = -1 }
199 static const Jim_Nvp nvp_target_state[] = {
200 { .name = "unknown", .value = TARGET_UNKNOWN },
201 { .name = "running", .value = TARGET_RUNNING },
202 { .name = "halted", .value = TARGET_HALTED },
203 { .name = "reset", .value = TARGET_RESET },
204 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
205 { .name = NULL, .value = -1 },
208 static const Jim_Nvp nvp_target_debug_reason [] = {
209 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
210 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
211 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
212 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
213 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
214 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
215 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
216 { .name = NULL, .value = -1 },
219 static const Jim_Nvp nvp_target_endian[] = {
220 { .name = "big", .value = TARGET_BIG_ENDIAN },
221 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
222 { .name = "be", .value = TARGET_BIG_ENDIAN },
223 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
224 { .name = NULL, .value = -1 },
227 static const Jim_Nvp nvp_reset_modes[] = {
228 { .name = "unknown", .value = RESET_UNKNOWN },
229 { .name = "run" , .value = RESET_RUN },
230 { .name = "halt" , .value = RESET_HALT },
231 { .name = "init" , .value = RESET_INIT },
232 { .name = NULL , .value = -1 },
235 const char *debug_reason_name(struct target *t)
237 const char *cp;
239 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
240 t->debug_reason)->name;
241 if (!cp) {
242 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
243 cp = "(*BUG*unknown*BUG*)";
245 return cp;
248 const char *
249 target_state_name( struct target *t )
251 const char *cp;
252 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
253 if( !cp ){
254 LOG_ERROR("Invalid target state: %d", (int)(t->state));
255 cp = "(*BUG*unknown*BUG*)";
257 return cp;
260 /* determine the number of the new target */
261 static int new_target_number(void)
263 struct target *t;
264 int x;
266 /* number is 0 based */
267 x = -1;
268 t = all_targets;
269 while (t) {
270 if (x < t->target_number) {
271 x = t->target_number;
273 t = t->next;
275 return x + 1;
278 /* read a uint32_t from a buffer in target memory endianness */
279 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
281 if (target->endianness == TARGET_LITTLE_ENDIAN)
282 return le_to_h_u32(buffer);
283 else
284 return be_to_h_u32(buffer);
287 /* read a uint24_t from a buffer in target memory endianness */
288 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
290 if (target->endianness == TARGET_LITTLE_ENDIAN)
291 return le_to_h_u24(buffer);
292 else
293 return be_to_h_u24(buffer);
296 /* read a uint16_t from a buffer in target memory endianness */
297 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
299 if (target->endianness == TARGET_LITTLE_ENDIAN)
300 return le_to_h_u16(buffer);
301 else
302 return be_to_h_u16(buffer);
305 /* read a uint8_t from a buffer in target memory endianness */
306 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
308 return *buffer & 0x0ff;
311 /* write a uint32_t to a buffer in target memory endianness */
312 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
314 if (target->endianness == TARGET_LITTLE_ENDIAN)
315 h_u32_to_le(buffer, value);
316 else
317 h_u32_to_be(buffer, value);
320 /* write a uint24_t to a buffer in target memory endianness */
321 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
323 if (target->endianness == TARGET_LITTLE_ENDIAN)
324 h_u24_to_le(buffer, value);
325 else
326 h_u24_to_be(buffer, value);
329 /* write a uint16_t to a buffer in target memory endianness */
330 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
332 if (target->endianness == TARGET_LITTLE_ENDIAN)
333 h_u16_to_le(buffer, value);
334 else
335 h_u16_to_be(buffer, value);
338 /* write a uint8_t to a buffer in target memory endianness */
339 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
341 *buffer = value;
344 /* return a pointer to a configured target; id is name or number */
345 struct target *get_target(const char *id)
347 struct target *target;
349 /* try as tcltarget name */
350 for (target = all_targets; target; target = target->next) {
351 if (target->cmd_name == NULL)
352 continue;
353 if (strcmp(id, target->cmd_name) == 0)
354 return target;
357 /* It's OK to remove this fallback sometime after August 2010 or so */
359 /* no match, try as number */
360 unsigned num;
361 if (parse_uint(id, &num) != ERROR_OK)
362 return NULL;
364 for (target = all_targets; target; target = target->next) {
365 if (target->target_number == (int)num) {
366 LOG_WARNING("use '%s' as target identifier, not '%u'",
367 target->cmd_name, num);
368 return target;
372 return NULL;
375 /* returns a pointer to the n-th configured target */
376 static struct target *get_target_by_num(int num)
378 struct target *target = all_targets;
380 while (target) {
381 if (target->target_number == num) {
382 return target;
384 target = target->next;
387 return NULL;
390 struct target* get_current_target(struct command_context *cmd_ctx)
392 struct target *target = get_target_by_num(cmd_ctx->current_target);
394 if (target == NULL)
396 LOG_ERROR("BUG: current_target out of bounds");
397 exit(-1);
400 return target;
403 int target_poll(struct target *target)
405 int retval;
407 /* We can't poll until after examine */
408 if (!target_was_examined(target))
410 /* Fail silently lest we pollute the log */
411 return ERROR_FAIL;
414 retval = target->type->poll(target);
415 if (retval != ERROR_OK)
416 return retval;
418 if (target->halt_issued)
420 if (target->state == TARGET_HALTED)
422 target->halt_issued = false;
423 } else
425 long long t = timeval_ms() - target->halt_issued_time;
426 if (t>1000)
428 target->halt_issued = false;
429 LOG_INFO("Halt timed out, wake up GDB.");
430 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
435 return ERROR_OK;
438 int target_halt(struct target *target)
440 int retval;
441 /* We can't poll until after examine */
442 if (!target_was_examined(target))
444 LOG_ERROR("Target not examined yet");
445 return ERROR_FAIL;
448 retval = target->type->halt(target);
449 if (retval != ERROR_OK)
450 return retval;
452 target->halt_issued = true;
453 target->halt_issued_time = timeval_ms();
455 return ERROR_OK;
459 * Make the target (re)start executing using its saved execution
460 * context (possibly with some modifications).
462 * @param target Which target should start executing.
463 * @param current True to use the target's saved program counter instead
464 * of the address parameter
465 * @param address Optionally used as the program counter.
466 * @param handle_breakpoints True iff breakpoints at the resumption PC
467 * should be skipped. (For example, maybe execution was stopped by
468 * such a breakpoint, in which case it would be counterprodutive to
469 * let it re-trigger.
470 * @param debug_execution False if all working areas allocated by OpenOCD
471 * should be released and/or restored to their original contents.
472 * (This would for example be true to run some downloaded "helper"
473 * algorithm code, which resides in one such working buffer and uses
474 * another for data storage.)
476 * @todo Resolve the ambiguity about what the "debug_execution" flag
477 * signifies. For example, Target implementations don't agree on how
478 * it relates to invalidation of the register cache, or to whether
479 * breakpoints and watchpoints should be enabled. (It would seem wrong
480 * to enable breakpoints when running downloaded "helper" algorithms
481 * (debug_execution true), since the breakpoints would be set to match
482 * target firmware being debugged, not the helper algorithm.... and
483 * enabling them could cause such helpers to malfunction (for example,
484 * by overwriting data with a breakpoint instruction. On the other
485 * hand the infrastructure for running such helpers might use this
486 * procedure but rely on hardware breakpoint to detect termination.)
488 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
490 int retval;
492 /* We can't poll until after examine */
493 if (!target_was_examined(target))
495 LOG_ERROR("Target not examined yet");
496 return ERROR_FAIL;
499 /* note that resume *must* be asynchronous. The CPU can halt before
500 * we poll. The CPU can even halt at the current PC as a result of
501 * a software breakpoint being inserted by (a bug?) the application.
503 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
504 return retval;
506 return retval;
509 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
511 char buf[100];
512 int retval;
513 Jim_Nvp *n;
514 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
515 if (n->name == NULL) {
516 LOG_ERROR("invalid reset mode");
517 return ERROR_FAIL;
520 /* disable polling during reset to make reset event scripts
521 * more predictable, i.e. dr/irscan & pathmove in events will
522 * not have JTAG operations injected into the middle of a sequence.
524 bool save_poll = jtag_poll_get_enabled();
526 jtag_poll_set_enabled(false);
528 sprintf(buf, "ocd_process_reset %s", n->name);
529 retval = Jim_Eval(cmd_ctx->interp, buf);
531 jtag_poll_set_enabled(save_poll);
533 if (retval != JIM_OK) {
534 Jim_MakeErrorMessage(cmd_ctx->interp);
535 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
536 return ERROR_FAIL;
539 /* We want any events to be processed before the prompt */
540 retval = target_call_timer_callbacks_now();
542 struct target *target;
543 for (target = all_targets; target; target = target->next) {
544 target->type->check_reset(target);
547 return retval;
550 static int identity_virt2phys(struct target *target,
551 uint32_t virtual, uint32_t *physical)
553 *physical = virtual;
554 return ERROR_OK;
557 static int no_mmu(struct target *target, int *enabled)
559 *enabled = 0;
560 return ERROR_OK;
563 static int default_examine(struct target *target)
565 target_set_examined(target);
566 return ERROR_OK;
569 /* no check by default */
570 static int default_check_reset(struct target *target)
572 return ERROR_OK;
575 int target_examine_one(struct target *target)
577 return target->type->examine(target);
580 static int jtag_enable_callback(enum jtag_event event, void *priv)
582 struct target *target = priv;
584 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
585 return ERROR_OK;
587 jtag_unregister_event_callback(jtag_enable_callback, target);
588 return target_examine_one(target);
592 /* Targets that correctly implement init + examine, i.e.
593 * no communication with target during init:
595 * XScale
597 int target_examine(void)
599 int retval = ERROR_OK;
600 struct target *target;
602 for (target = all_targets; target; target = target->next)
604 /* defer examination, but don't skip it */
605 if (!target->tap->enabled) {
606 jtag_register_event_callback(jtag_enable_callback,
607 target);
608 continue;
610 if ((retval = target_examine_one(target)) != ERROR_OK)
611 return retval;
613 return retval;
615 const char *target_type_name(struct target *target)
617 return target->type->name;
620 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
622 if (!target_was_examined(target))
624 LOG_ERROR("Target not examined yet");
625 return ERROR_FAIL;
627 return target->type->write_memory_imp(target, address, size, count, buffer);
630 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
632 if (!target_was_examined(target))
634 LOG_ERROR("Target not examined yet");
635 return ERROR_FAIL;
637 return target->type->read_memory_imp(target, address, size, count, buffer);
640 static int target_soft_reset_halt_imp(struct target *target)
642 if (!target_was_examined(target))
644 LOG_ERROR("Target not examined yet");
645 return ERROR_FAIL;
647 if (!target->type->soft_reset_halt_imp) {
648 LOG_ERROR("Target %s does not support soft_reset_halt",
649 target_name(target));
650 return ERROR_FAIL;
652 return target->type->soft_reset_halt_imp(target);
656 * Downloads a target-specific native code algorithm to the target,
657 * and executes it. * Note that some targets may need to set up, enable,
658 * and tear down a breakpoint (hard or * soft) to detect algorithm
659 * termination, while others may support lower overhead schemes where
660 * soft breakpoints embedded in the algorithm automatically terminate the
661 * algorithm.
663 * @param target used to run the algorithm
664 * @param arch_info target-specific description of the algorithm.
666 int target_run_algorithm(struct target *target,
667 int num_mem_params, struct mem_param *mem_params,
668 int num_reg_params, struct reg_param *reg_param,
669 uint32_t entry_point, uint32_t exit_point,
670 int timeout_ms, void *arch_info)
672 int retval = ERROR_FAIL;
674 if (!target_was_examined(target))
676 LOG_ERROR("Target not examined yet");
677 goto done;
679 if (!target->type->run_algorithm) {
680 LOG_ERROR("Target type '%s' does not support %s",
681 target_type_name(target), __func__);
682 goto done;
685 target->running_alg = true;
686 retval = target->type->run_algorithm(target,
687 num_mem_params, mem_params,
688 num_reg_params, reg_param,
689 entry_point, exit_point, timeout_ms, arch_info);
690 target->running_alg = false;
692 done:
693 return retval;
697 int target_read_memory(struct target *target,
698 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
700 return target->type->read_memory(target, address, size, count, buffer);
703 static int target_read_phys_memory(struct target *target,
704 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
706 return target->type->read_phys_memory(target, address, size, count, buffer);
709 int target_write_memory(struct target *target,
710 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
712 return target->type->write_memory(target, address, size, count, buffer);
715 static int target_write_phys_memory(struct target *target,
716 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
718 return target->type->write_phys_memory(target, address, size, count, buffer);
721 int target_bulk_write_memory(struct target *target,
722 uint32_t address, uint32_t count, uint8_t *buffer)
724 return target->type->bulk_write_memory(target, address, count, buffer);
727 int target_add_breakpoint(struct target *target,
728 struct breakpoint *breakpoint)
730 if (target->state != TARGET_HALTED) {
731 LOG_WARNING("target %s is not halted", target->cmd_name);
732 return ERROR_TARGET_NOT_HALTED;
734 return target->type->add_breakpoint(target, breakpoint);
736 int target_remove_breakpoint(struct target *target,
737 struct breakpoint *breakpoint)
739 return target->type->remove_breakpoint(target, breakpoint);
742 int target_add_watchpoint(struct target *target,
743 struct watchpoint *watchpoint)
745 if (target->state != TARGET_HALTED) {
746 LOG_WARNING("target %s is not halted", target->cmd_name);
747 return ERROR_TARGET_NOT_HALTED;
749 return target->type->add_watchpoint(target, watchpoint);
751 int target_remove_watchpoint(struct target *target,
752 struct watchpoint *watchpoint)
754 return target->type->remove_watchpoint(target, watchpoint);
757 int target_get_gdb_reg_list(struct target *target,
758 struct reg **reg_list[], int *reg_list_size)
760 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
762 int target_step(struct target *target,
763 int current, uint32_t address, int handle_breakpoints)
765 return target->type->step(target, current, address, handle_breakpoints);
770 * Reset the @c examined flag for the given target.
771 * Pure paranoia -- targets are zeroed on allocation.
773 static void target_reset_examined(struct target *target)
775 target->examined = false;
778 static int
779 err_read_phys_memory(struct target *target, uint32_t address,
780 uint32_t size, uint32_t count, uint8_t *buffer)
782 LOG_ERROR("Not implemented: %s", __func__);
783 return ERROR_FAIL;
786 static int
787 err_write_phys_memory(struct target *target, uint32_t address,
788 uint32_t size, uint32_t count, uint8_t *buffer)
790 LOG_ERROR("Not implemented: %s", __func__);
791 return ERROR_FAIL;
794 static int handle_target(void *priv);
796 static int target_init_one(struct command_context *cmd_ctx,
797 struct target *target)
799 target_reset_examined(target);
801 struct target_type *type = target->type;
802 if (type->examine == NULL)
803 type->examine = default_examine;
805 if (type->check_reset== NULL)
806 type->check_reset = default_check_reset;
808 int retval = type->init_target(cmd_ctx, target);
809 if (ERROR_OK != retval)
811 LOG_ERROR("target '%s' init failed", target_name(target));
812 return retval;
816 * @todo get rid of those *memory_imp() methods, now that all
817 * callers are using target_*_memory() accessors ... and make
818 * sure the "physical" paths handle the same issues.
820 /* a non-invasive way(in terms of patches) to add some code that
821 * runs before the type->write/read_memory implementation
823 type->write_memory_imp = target->type->write_memory;
824 type->write_memory = target_write_memory_imp;
826 type->read_memory_imp = target->type->read_memory;
827 type->read_memory = target_read_memory_imp;
829 type->soft_reset_halt_imp = target->type->soft_reset_halt;
830 type->soft_reset_halt = target_soft_reset_halt_imp;
832 /* Sanity-check MMU support ... stub in what we must, to help
833 * implement it in stages, but warn if we need to do so.
835 if (type->mmu)
837 if (type->write_phys_memory == NULL)
839 LOG_ERROR("type '%s' is missing write_phys_memory",
840 type->name);
841 type->write_phys_memory = err_write_phys_memory;
843 if (type->read_phys_memory == NULL)
845 LOG_ERROR("type '%s' is missing read_phys_memory",
846 type->name);
847 type->read_phys_memory = err_read_phys_memory;
849 if (type->virt2phys == NULL)
851 LOG_ERROR("type '%s' is missing virt2phys", type->name);
852 type->virt2phys = identity_virt2phys;
855 else
857 /* Make sure no-MMU targets all behave the same: make no
858 * distinction between physical and virtual addresses, and
859 * ensure that virt2phys() is always an identity mapping.
861 if (type->write_phys_memory || type->read_phys_memory
862 || type->virt2phys)
864 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
867 type->mmu = no_mmu;
868 type->write_phys_memory = type->write_memory;
869 type->read_phys_memory = type->read_memory;
870 type->virt2phys = identity_virt2phys;
873 if (target->type->read_buffer == NULL)
874 target->type->read_buffer = target_read_buffer_default;
876 if (target->type->write_buffer == NULL)
877 target->type->write_buffer = target_write_buffer_default;
879 return ERROR_OK;
882 static int target_init(struct command_context *cmd_ctx)
884 struct target *target;
885 int retval;
887 for (target = all_targets; target; target = target->next)
889 retval = target_init_one(cmd_ctx, target);
890 if (ERROR_OK != retval)
891 return retval;
894 if (!all_targets)
895 return ERROR_OK;
897 retval = target_register_user_commands(cmd_ctx);
898 if (ERROR_OK != retval)
899 return retval;
901 retval = target_register_timer_callback(&handle_target,
902 polling_interval, 1, cmd_ctx->interp);
903 if (ERROR_OK != retval)
904 return retval;
906 return ERROR_OK;
909 COMMAND_HANDLER(handle_target_init_command)
911 if (CMD_ARGC != 0)
912 return ERROR_COMMAND_SYNTAX_ERROR;
914 static bool target_initialized = false;
915 if (target_initialized)
917 LOG_INFO("'target init' has already been called");
918 return ERROR_OK;
920 target_initialized = true;
922 LOG_DEBUG("Initializing targets...");
923 return target_init(CMD_CTX);
926 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
928 struct target_event_callback **callbacks_p = &target_event_callbacks;
930 if (callback == NULL)
932 return ERROR_INVALID_ARGUMENTS;
935 if (*callbacks_p)
937 while ((*callbacks_p)->next)
938 callbacks_p = &((*callbacks_p)->next);
939 callbacks_p = &((*callbacks_p)->next);
942 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
943 (*callbacks_p)->callback = callback;
944 (*callbacks_p)->priv = priv;
945 (*callbacks_p)->next = NULL;
947 return ERROR_OK;
950 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
952 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
953 struct timeval now;
955 if (callback == NULL)
957 return ERROR_INVALID_ARGUMENTS;
960 if (*callbacks_p)
962 while ((*callbacks_p)->next)
963 callbacks_p = &((*callbacks_p)->next);
964 callbacks_p = &((*callbacks_p)->next);
967 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
968 (*callbacks_p)->callback = callback;
969 (*callbacks_p)->periodic = periodic;
970 (*callbacks_p)->time_ms = time_ms;
972 gettimeofday(&now, NULL);
973 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
974 time_ms -= (time_ms % 1000);
975 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
976 if ((*callbacks_p)->when.tv_usec > 1000000)
978 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
979 (*callbacks_p)->when.tv_sec += 1;
982 (*callbacks_p)->priv = priv;
983 (*callbacks_p)->next = NULL;
985 return ERROR_OK;
988 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
990 struct target_event_callback **p = &target_event_callbacks;
991 struct target_event_callback *c = target_event_callbacks;
993 if (callback == NULL)
995 return ERROR_INVALID_ARGUMENTS;
998 while (c)
1000 struct target_event_callback *next = c->next;
1001 if ((c->callback == callback) && (c->priv == priv))
1003 *p = next;
1004 free(c);
1005 return ERROR_OK;
1007 else
1008 p = &(c->next);
1009 c = next;
1012 return ERROR_OK;
1015 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1017 struct target_timer_callback **p = &target_timer_callbacks;
1018 struct target_timer_callback *c = target_timer_callbacks;
1020 if (callback == NULL)
1022 return ERROR_INVALID_ARGUMENTS;
1025 while (c)
1027 struct target_timer_callback *next = c->next;
1028 if ((c->callback == callback) && (c->priv == priv))
1030 *p = next;
1031 free(c);
1032 return ERROR_OK;
1034 else
1035 p = &(c->next);
1036 c = next;
1039 return ERROR_OK;
1042 int target_call_event_callbacks(struct target *target, enum target_event event)
1044 struct target_event_callback *callback = target_event_callbacks;
1045 struct target_event_callback *next_callback;
1047 if (event == TARGET_EVENT_HALTED)
1049 /* execute early halted first */
1050 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1053 LOG_DEBUG("target event %i (%s)",
1054 event,
1055 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1057 target_handle_event(target, event);
1059 while (callback)
1061 next_callback = callback->next;
1062 callback->callback(target, event, callback->priv);
1063 callback = next_callback;
1066 return ERROR_OK;
1069 static int target_timer_callback_periodic_restart(
1070 struct target_timer_callback *cb, struct timeval *now)
1072 int time_ms = cb->time_ms;
1073 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1074 time_ms -= (time_ms % 1000);
1075 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1076 if (cb->when.tv_usec > 1000000)
1078 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1079 cb->when.tv_sec += 1;
1081 return ERROR_OK;
1084 static int target_call_timer_callback(struct target_timer_callback *cb,
1085 struct timeval *now)
1087 cb->callback(cb->priv);
1089 if (cb->periodic)
1090 return target_timer_callback_periodic_restart(cb, now);
1092 return target_unregister_timer_callback(cb->callback, cb->priv);
1095 static int target_call_timer_callbacks_check_time(int checktime)
1097 keep_alive();
1099 struct timeval now;
1100 gettimeofday(&now, NULL);
1102 struct target_timer_callback *callback = target_timer_callbacks;
1103 while (callback)
1105 // cleaning up may unregister and free this callback
1106 struct target_timer_callback *next_callback = callback->next;
1108 bool call_it = callback->callback &&
1109 ((!checktime && callback->periodic) ||
1110 now.tv_sec > callback->when.tv_sec ||
1111 (now.tv_sec == callback->when.tv_sec &&
1112 now.tv_usec >= callback->when.tv_usec));
1114 if (call_it)
1116 int retval = target_call_timer_callback(callback, &now);
1117 if (retval != ERROR_OK)
1118 return retval;
1121 callback = next_callback;
1124 return ERROR_OK;
1127 int target_call_timer_callbacks(void)
1129 return target_call_timer_callbacks_check_time(1);
1132 /* invoke periodic callbacks immediately */
1133 int target_call_timer_callbacks_now(void)
1135 return target_call_timer_callbacks_check_time(0);
1138 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1140 struct working_area *c = target->working_areas;
1141 struct working_area *new_wa = NULL;
1143 /* Reevaluate working area address based on MMU state*/
1144 if (target->working_areas == NULL)
1146 int retval;
1147 int enabled;
1149 retval = target->type->mmu(target, &enabled);
1150 if (retval != ERROR_OK)
1152 return retval;
1155 if (!enabled) {
1156 if (target->working_area_phys_spec) {
1157 LOG_DEBUG("MMU disabled, using physical "
1158 "address for working memory 0x%08x",
1159 (unsigned)target->working_area_phys);
1160 target->working_area = target->working_area_phys;
1161 } else {
1162 LOG_ERROR("No working memory available. "
1163 "Specify -work-area-phys to target.");
1164 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1166 } else {
1167 if (target->working_area_virt_spec) {
1168 LOG_DEBUG("MMU enabled, using virtual "
1169 "address for working memory 0x%08x",
1170 (unsigned)target->working_area_virt);
1171 target->working_area = target->working_area_virt;
1172 } else {
1173 LOG_ERROR("No working memory available. "
1174 "Specify -work-area-virt to target.");
1175 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1180 /* only allocate multiples of 4 byte */
1181 if (size % 4)
1183 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1184 size = (size + 3) & (~3);
1187 /* see if there's already a matching working area */
1188 while (c)
1190 if ((c->free) && (c->size == size))
1192 new_wa = c;
1193 break;
1195 c = c->next;
1198 /* if not, allocate a new one */
1199 if (!new_wa)
1201 struct working_area **p = &target->working_areas;
1202 uint32_t first_free = target->working_area;
1203 uint32_t free_size = target->working_area_size;
1205 c = target->working_areas;
1206 while (c)
1208 first_free += c->size;
1209 free_size -= c->size;
1210 p = &c->next;
1211 c = c->next;
1214 if (free_size < size)
1216 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1219 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1221 new_wa = malloc(sizeof(struct working_area));
1222 new_wa->next = NULL;
1223 new_wa->size = size;
1224 new_wa->address = first_free;
1226 if (target->backup_working_area)
1228 int retval;
1229 new_wa->backup = malloc(new_wa->size);
1230 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1232 free(new_wa->backup);
1233 free(new_wa);
1234 return retval;
1237 else
1239 new_wa->backup = NULL;
1242 /* put new entry in list */
1243 *p = new_wa;
1246 /* mark as used, and return the new (reused) area */
1247 new_wa->free = false;
1248 *area = new_wa;
1250 /* user pointer */
1251 new_wa->user = area;
1253 return ERROR_OK;
1256 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1258 int retval;
1260 retval = target_alloc_working_area_try(target, size, area);
1261 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1263 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1265 return retval;
1269 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1271 if (area->free)
1272 return ERROR_OK;
1274 if (restore && target->backup_working_area)
1276 int retval;
1277 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1278 return retval;
1281 area->free = true;
1283 /* mark user pointer invalid */
1284 *area->user = NULL;
1285 area->user = NULL;
1287 return ERROR_OK;
1290 int target_free_working_area(struct target *target, struct working_area *area)
1292 return target_free_working_area_restore(target, area, 1);
1295 /* free resources and restore memory, if restoring memory fails,
1296 * free up resources anyway
1298 static void target_free_all_working_areas_restore(struct target *target, int restore)
1300 struct working_area *c = target->working_areas;
1302 while (c)
1304 struct working_area *next = c->next;
1305 target_free_working_area_restore(target, c, restore);
1307 if (c->backup)
1308 free(c->backup);
1310 free(c);
1312 c = next;
1315 target->working_areas = NULL;
1318 void target_free_all_working_areas(struct target *target)
1320 target_free_all_working_areas_restore(target, 1);
1323 int target_arch_state(struct target *target)
1325 int retval;
1326 if (target == NULL)
1328 LOG_USER("No target has been configured");
1329 return ERROR_OK;
1332 LOG_USER("target state: %s", target_state_name( target ));
1334 if (target->state != TARGET_HALTED)
1335 return ERROR_OK;
1337 retval = target->type->arch_state(target);
1338 return retval;
1341 /* Single aligned words are guaranteed to use 16 or 32 bit access
1342 * mode respectively, otherwise data is handled as quickly as
1343 * possible
1345 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1347 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1348 (int)size, (unsigned)address);
1350 if (!target_was_examined(target))
1352 LOG_ERROR("Target not examined yet");
1353 return ERROR_FAIL;
1356 if (size == 0) {
1357 return ERROR_OK;
1360 if ((address + size - 1) < address)
1362 /* GDB can request this when e.g. PC is 0xfffffffc*/
1363 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1364 (unsigned)address,
1365 (unsigned)size);
1366 return ERROR_FAIL;
1369 return target->type->write_buffer(target, address, size, buffer);
1372 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1374 int retval = ERROR_OK;
1376 if (((address % 2) == 0) && (size == 2))
1378 return target_write_memory(target, address, 2, 1, buffer);
1381 /* handle unaligned head bytes */
1382 if (address % 4)
1384 uint32_t unaligned = 4 - (address % 4);
1386 if (unaligned > size)
1387 unaligned = size;
1389 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1390 return retval;
1392 buffer += unaligned;
1393 address += unaligned;
1394 size -= unaligned;
1397 /* handle aligned words */
1398 if (size >= 4)
1400 int aligned = size - (size % 4);
1402 /* use bulk writes above a certain limit. This may have to be changed */
1403 if (aligned > 128)
1405 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1406 return retval;
1408 else
1410 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1411 return retval;
1414 buffer += aligned;
1415 address += aligned;
1416 size -= aligned;
1419 /* handle tail writes of less than 4 bytes */
1420 if (size > 0)
1422 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1423 return retval;
1426 return retval;
1429 /* Single aligned words are guaranteed to use 16 or 32 bit access
1430 * mode respectively, otherwise data is handled as quickly as
1431 * possible
1433 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1435 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1436 (int)size, (unsigned)address);
1438 if (!target_was_examined(target))
1440 LOG_ERROR("Target not examined yet");
1441 return ERROR_FAIL;
1444 if (size == 0) {
1445 return ERROR_OK;
1448 if ((address + size - 1) < address)
1450 /* GDB can request this when e.g. PC is 0xfffffffc*/
1451 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1452 address,
1453 size);
1454 return ERROR_FAIL;
1457 return target->type->read_buffer(target, address, size, buffer);
1460 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1462 int retval = ERROR_OK;
1464 if (((address % 2) == 0) && (size == 2))
1466 return target_read_memory(target, address, 2, 1, buffer);
1469 /* handle unaligned head bytes */
1470 if (address % 4)
1472 uint32_t unaligned = 4 - (address % 4);
1474 if (unaligned > size)
1475 unaligned = size;
1477 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1478 return retval;
1480 buffer += unaligned;
1481 address += unaligned;
1482 size -= unaligned;
1485 /* handle aligned words */
1486 if (size >= 4)
1488 int aligned = size - (size % 4);
1490 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1491 return retval;
1493 buffer += aligned;
1494 address += aligned;
1495 size -= aligned;
1498 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1499 if(size >=2)
1501 int aligned = size - (size%2);
1502 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1503 if (retval != ERROR_OK)
1504 return retval;
1506 buffer += aligned;
1507 address += aligned;
1508 size -= aligned;
1510 /* handle tail writes of less than 4 bytes */
1511 if (size > 0)
1513 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1514 return retval;
1517 return ERROR_OK;
1520 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1522 uint8_t *buffer;
1523 int retval;
1524 uint32_t i;
1525 uint32_t checksum = 0;
1526 if (!target_was_examined(target))
1528 LOG_ERROR("Target not examined yet");
1529 return ERROR_FAIL;
1532 if ((retval = target->type->checksum_memory(target, address,
1533 size, &checksum)) != ERROR_OK)
1535 buffer = malloc(size);
1536 if (buffer == NULL)
1538 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1539 return ERROR_INVALID_ARGUMENTS;
1541 retval = target_read_buffer(target, address, size, buffer);
1542 if (retval != ERROR_OK)
1544 free(buffer);
1545 return retval;
1548 /* convert to target endianness */
1549 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1551 uint32_t target_data;
1552 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1553 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1556 retval = image_calculate_checksum(buffer, size, &checksum);
1557 free(buffer);
1560 *crc = checksum;
1562 return retval;
1565 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1567 int retval;
1568 if (!target_was_examined(target))
1570 LOG_ERROR("Target not examined yet");
1571 return ERROR_FAIL;
1574 if (target->type->blank_check_memory == 0)
1575 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1577 retval = target->type->blank_check_memory(target, address, size, blank);
1579 return retval;
1582 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1584 uint8_t value_buf[4];
1585 if (!target_was_examined(target))
1587 LOG_ERROR("Target not examined yet");
1588 return ERROR_FAIL;
1591 int retval = target_read_memory(target, address, 4, 1, value_buf);
1593 if (retval == ERROR_OK)
1595 *value = target_buffer_get_u32(target, value_buf);
1596 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1597 address,
1598 *value);
1600 else
1602 *value = 0x0;
1603 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1604 address);
1607 return retval;
1610 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1612 uint8_t value_buf[2];
1613 if (!target_was_examined(target))
1615 LOG_ERROR("Target not examined yet");
1616 return ERROR_FAIL;
1619 int retval = target_read_memory(target, address, 2, 1, value_buf);
1621 if (retval == ERROR_OK)
1623 *value = target_buffer_get_u16(target, value_buf);
1624 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1625 address,
1626 *value);
1628 else
1630 *value = 0x0;
1631 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1632 address);
1635 return retval;
1638 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1640 int retval = target_read_memory(target, address, 1, 1, value);
1641 if (!target_was_examined(target))
1643 LOG_ERROR("Target not examined yet");
1644 return ERROR_FAIL;
1647 if (retval == ERROR_OK)
1649 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1650 address,
1651 *value);
1653 else
1655 *value = 0x0;
1656 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1657 address);
1660 return retval;
1663 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1665 int retval;
1666 uint8_t value_buf[4];
1667 if (!target_was_examined(target))
1669 LOG_ERROR("Target not examined yet");
1670 return ERROR_FAIL;
1673 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1674 address,
1675 value);
1677 target_buffer_set_u32(target, value_buf, value);
1678 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1680 LOG_DEBUG("failed: %i", retval);
1683 return retval;
1686 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1688 int retval;
1689 uint8_t value_buf[2];
1690 if (!target_was_examined(target))
1692 LOG_ERROR("Target not examined yet");
1693 return ERROR_FAIL;
1696 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1697 address,
1698 value);
1700 target_buffer_set_u16(target, value_buf, value);
1701 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1703 LOG_DEBUG("failed: %i", retval);
1706 return retval;
1709 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1711 int retval;
1712 if (!target_was_examined(target))
1714 LOG_ERROR("Target not examined yet");
1715 return ERROR_FAIL;
1718 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1719 address, value);
1721 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1723 LOG_DEBUG("failed: %i", retval);
1726 return retval;
1729 COMMAND_HANDLER(handle_targets_command)
1731 struct target *target = all_targets;
1733 if (CMD_ARGC == 1)
1735 target = get_target(CMD_ARGV[0]);
1736 if (target == NULL) {
1737 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1738 goto DumpTargets;
1740 if (!target->tap->enabled) {
1741 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1742 "can't be the current target\n",
1743 target->tap->dotted_name);
1744 return ERROR_FAIL;
1747 CMD_CTX->current_target = target->target_number;
1748 return ERROR_OK;
1750 DumpTargets:
1752 target = all_targets;
1753 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1754 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1755 while (target)
1757 const char *state;
1758 char marker = ' ';
1760 if (target->tap->enabled)
1761 state = target_state_name( target );
1762 else
1763 state = "tap-disabled";
1765 if (CMD_CTX->current_target == target->target_number)
1766 marker = '*';
1768 /* keep columns lined up to match the headers above */
1769 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1770 target->target_number,
1771 marker,
1772 target_name(target),
1773 target_type_name(target),
1774 Jim_Nvp_value2name_simple(nvp_target_endian,
1775 target->endianness)->name,
1776 target->tap->dotted_name,
1777 state);
1778 target = target->next;
1781 return ERROR_OK;
1784 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1786 static int powerDropout;
1787 static int srstAsserted;
1789 static int runPowerRestore;
1790 static int runPowerDropout;
1791 static int runSrstAsserted;
1792 static int runSrstDeasserted;
1794 static int sense_handler(void)
1796 static int prevSrstAsserted = 0;
1797 static int prevPowerdropout = 0;
1799 int retval;
1800 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1801 return retval;
1803 int powerRestored;
1804 powerRestored = prevPowerdropout && !powerDropout;
1805 if (powerRestored)
1807 runPowerRestore = 1;
1810 long long current = timeval_ms();
1811 static long long lastPower = 0;
1812 int waitMore = lastPower + 2000 > current;
1813 if (powerDropout && !waitMore)
1815 runPowerDropout = 1;
1816 lastPower = current;
1819 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1820 return retval;
1822 int srstDeasserted;
1823 srstDeasserted = prevSrstAsserted && !srstAsserted;
1825 static long long lastSrst = 0;
1826 waitMore = lastSrst + 2000 > current;
1827 if (srstDeasserted && !waitMore)
1829 runSrstDeasserted = 1;
1830 lastSrst = current;
1833 if (!prevSrstAsserted && srstAsserted)
1835 runSrstAsserted = 1;
1838 prevSrstAsserted = srstAsserted;
1839 prevPowerdropout = powerDropout;
1841 if (srstDeasserted || powerRestored)
1843 /* Other than logging the event we can't do anything here.
1844 * Issuing a reset is a particularly bad idea as we might
1845 * be inside a reset already.
1849 return ERROR_OK;
1852 static int backoff_times = 0;
1853 static int backoff_count = 0;
1855 /* process target state changes */
1856 static int handle_target(void *priv)
1858 Jim_Interp *interp = (Jim_Interp *)priv;
1859 int retval = ERROR_OK;
1861 if (!is_jtag_poll_safe())
1863 /* polling is disabled currently */
1864 return ERROR_OK;
1867 /* we do not want to recurse here... */
1868 static int recursive = 0;
1869 if (! recursive)
1871 recursive = 1;
1872 sense_handler();
1873 /* danger! running these procedures can trigger srst assertions and power dropouts.
1874 * We need to avoid an infinite loop/recursion here and we do that by
1875 * clearing the flags after running these events.
1877 int did_something = 0;
1878 if (runSrstAsserted)
1880 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1881 Jim_Eval(interp, "srst_asserted");
1882 did_something = 1;
1884 if (runSrstDeasserted)
1886 Jim_Eval(interp, "srst_deasserted");
1887 did_something = 1;
1889 if (runPowerDropout)
1891 LOG_INFO("Power dropout detected, running power_dropout proc.");
1892 Jim_Eval(interp, "power_dropout");
1893 did_something = 1;
1895 if (runPowerRestore)
1897 Jim_Eval(interp, "power_restore");
1898 did_something = 1;
1901 if (did_something)
1903 /* clear detect flags */
1904 sense_handler();
1907 /* clear action flags */
1909 runSrstAsserted = 0;
1910 runSrstDeasserted = 0;
1911 runPowerRestore = 0;
1912 runPowerDropout = 0;
1914 recursive = 0;
1917 if (backoff_times > backoff_count)
1919 /* do not poll this time as we failed previously */
1920 backoff_count++;
1921 return ERROR_OK;
1923 backoff_count = 0;
1925 /* Poll targets for state changes unless that's globally disabled.
1926 * Skip targets that are currently disabled.
1928 for (struct target *target = all_targets;
1929 is_jtag_poll_safe() && target;
1930 target = target->next)
1932 if (!target->tap->enabled)
1933 continue;
1935 /* only poll target if we've got power and srst isn't asserted */
1936 if (!powerDropout && !srstAsserted)
1938 /* polling may fail silently until the target has been examined */
1939 if ((retval = target_poll(target)) != ERROR_OK)
1941 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1942 if (backoff_times * polling_interval < 5000)
1944 backoff_times *= 2;
1945 backoff_times++;
1947 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1949 /* Tell GDB to halt the debugger. This allows the user to
1950 * run monitor commands to handle the situation.
1952 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1953 return retval;
1955 /* Since we succeeded, we reset backoff count */
1956 if (backoff_times > 0)
1958 LOG_USER("Polling succeeded again");
1960 backoff_times = 0;
1964 return retval;
1967 COMMAND_HANDLER(handle_reg_command)
1969 struct target *target;
1970 struct reg *reg = NULL;
1971 unsigned count = 0;
1972 char *value;
1974 LOG_DEBUG("-");
1976 target = get_current_target(CMD_CTX);
1978 /* list all available registers for the current target */
1979 if (CMD_ARGC == 0)
1981 struct reg_cache *cache = target->reg_cache;
1983 count = 0;
1984 while (cache)
1986 unsigned i;
1988 command_print(CMD_CTX, "===== %s", cache->name);
1990 for (i = 0, reg = cache->reg_list;
1991 i < cache->num_regs;
1992 i++, reg++, count++)
1994 /* only print cached values if they are valid */
1995 if (reg->valid) {
1996 value = buf_to_str(reg->value,
1997 reg->size, 16);
1998 command_print(CMD_CTX,
1999 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2000 count, reg->name,
2001 reg->size, value,
2002 reg->dirty
2003 ? " (dirty)"
2004 : "");
2005 free(value);
2006 } else {
2007 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2008 count, reg->name,
2009 reg->size) ;
2012 cache = cache->next;
2015 return ERROR_OK;
2018 /* access a single register by its ordinal number */
2019 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
2021 unsigned num;
2022 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2024 struct reg_cache *cache = target->reg_cache;
2025 count = 0;
2026 while (cache)
2028 unsigned i;
2029 for (i = 0; i < cache->num_regs; i++)
2031 if (count++ == num)
2033 reg = &cache->reg_list[i];
2034 break;
2037 if (reg)
2038 break;
2039 cache = cache->next;
2042 if (!reg)
2044 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2045 return ERROR_OK;
2047 } else /* access a single register by its name */
2049 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2051 if (!reg)
2053 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2054 return ERROR_OK;
2058 /* display a register */
2059 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2061 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2062 reg->valid = 0;
2064 if (reg->valid == 0)
2066 reg->type->get(reg);
2068 value = buf_to_str(reg->value, reg->size, 16);
2069 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2070 free(value);
2071 return ERROR_OK;
2074 /* set register value */
2075 if (CMD_ARGC == 2)
2077 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2078 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2080 reg->type->set(reg, buf);
2082 value = buf_to_str(reg->value, reg->size, 16);
2083 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2084 free(value);
2086 free(buf);
2088 return ERROR_OK;
2091 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2093 return ERROR_OK;
2096 COMMAND_HANDLER(handle_poll_command)
2098 int retval = ERROR_OK;
2099 struct target *target = get_current_target(CMD_CTX);
2101 if (CMD_ARGC == 0)
2103 command_print(CMD_CTX, "background polling: %s",
2104 jtag_poll_get_enabled() ? "on" : "off");
2105 command_print(CMD_CTX, "TAP: %s (%s)",
2106 target->tap->dotted_name,
2107 target->tap->enabled ? "enabled" : "disabled");
2108 if (!target->tap->enabled)
2109 return ERROR_OK;
2110 if ((retval = target_poll(target)) != ERROR_OK)
2111 return retval;
2112 if ((retval = target_arch_state(target)) != ERROR_OK)
2113 return retval;
2115 else if (CMD_ARGC == 1)
2117 bool enable;
2118 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2119 jtag_poll_set_enabled(enable);
2121 else
2123 return ERROR_COMMAND_SYNTAX_ERROR;
2126 return retval;
2129 COMMAND_HANDLER(handle_wait_halt_command)
2131 if (CMD_ARGC > 1)
2132 return ERROR_COMMAND_SYNTAX_ERROR;
2134 unsigned ms = 5000;
2135 if (1 == CMD_ARGC)
2137 int retval = parse_uint(CMD_ARGV[0], &ms);
2138 if (ERROR_OK != retval)
2140 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2141 return ERROR_COMMAND_SYNTAX_ERROR;
2143 // convert seconds (given) to milliseconds (needed)
2144 ms *= 1000;
2147 struct target *target = get_current_target(CMD_CTX);
2148 return target_wait_state(target, TARGET_HALTED, ms);
2151 /* wait for target state to change. The trick here is to have a low
2152 * latency for short waits and not to suck up all the CPU time
2153 * on longer waits.
2155 * After 500ms, keep_alive() is invoked
2157 int target_wait_state(struct target *target, enum target_state state, int ms)
2159 int retval;
2160 long long then = 0, cur;
2161 int once = 1;
2163 for (;;)
2165 if ((retval = target_poll(target)) != ERROR_OK)
2166 return retval;
2167 if (target->state == state)
2169 break;
2171 cur = timeval_ms();
2172 if (once)
2174 once = 0;
2175 then = timeval_ms();
2176 LOG_DEBUG("waiting for target %s...",
2177 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2180 if (cur-then > 500)
2182 keep_alive();
2185 if ((cur-then) > ms)
2187 LOG_ERROR("timed out while waiting for target %s",
2188 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2189 return ERROR_FAIL;
2193 return ERROR_OK;
2196 COMMAND_HANDLER(handle_halt_command)
2198 LOG_DEBUG("-");
2200 struct target *target = get_current_target(CMD_CTX);
2201 int retval = target_halt(target);
2202 if (ERROR_OK != retval)
2203 return retval;
2205 if (CMD_ARGC == 1)
2207 unsigned wait_local;
2208 retval = parse_uint(CMD_ARGV[0], &wait_local);
2209 if (ERROR_OK != retval)
2210 return ERROR_COMMAND_SYNTAX_ERROR;
2211 if (!wait_local)
2212 return ERROR_OK;
2215 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2218 COMMAND_HANDLER(handle_soft_reset_halt_command)
2220 struct target *target = get_current_target(CMD_CTX);
2222 LOG_USER("requesting target halt and executing a soft reset");
2224 target->type->soft_reset_halt(target);
2226 return ERROR_OK;
2229 COMMAND_HANDLER(handle_reset_command)
2231 if (CMD_ARGC > 1)
2232 return ERROR_COMMAND_SYNTAX_ERROR;
2234 enum target_reset_mode reset_mode = RESET_RUN;
2235 if (CMD_ARGC == 1)
2237 const Jim_Nvp *n;
2238 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2239 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2240 return ERROR_COMMAND_SYNTAX_ERROR;
2242 reset_mode = n->value;
2245 /* reset *all* targets */
2246 return target_process_reset(CMD_CTX, reset_mode);
2250 COMMAND_HANDLER(handle_resume_command)
2252 int current = 1;
2253 if (CMD_ARGC > 1)
2254 return ERROR_COMMAND_SYNTAX_ERROR;
2256 struct target *target = get_current_target(CMD_CTX);
2257 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2259 /* with no CMD_ARGV, resume from current pc, addr = 0,
2260 * with one arguments, addr = CMD_ARGV[0],
2261 * handle breakpoints, not debugging */
2262 uint32_t addr = 0;
2263 if (CMD_ARGC == 1)
2265 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2266 current = 0;
2269 return target_resume(target, current, addr, 1, 0);
2272 COMMAND_HANDLER(handle_step_command)
2274 if (CMD_ARGC > 1)
2275 return ERROR_COMMAND_SYNTAX_ERROR;
2277 LOG_DEBUG("-");
2279 /* with no CMD_ARGV, step from current pc, addr = 0,
2280 * with one argument addr = CMD_ARGV[0],
2281 * handle breakpoints, debugging */
2282 uint32_t addr = 0;
2283 int current_pc = 1;
2284 if (CMD_ARGC == 1)
2286 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2287 current_pc = 0;
2290 struct target *target = get_current_target(CMD_CTX);
2292 return target->type->step(target, current_pc, addr, 1);
2295 static void handle_md_output(struct command_context *cmd_ctx,
2296 struct target *target, uint32_t address, unsigned size,
2297 unsigned count, const uint8_t *buffer)
2299 const unsigned line_bytecnt = 32;
2300 unsigned line_modulo = line_bytecnt / size;
2302 char output[line_bytecnt * 4 + 1];
2303 unsigned output_len = 0;
2305 const char *value_fmt;
2306 switch (size) {
2307 case 4: value_fmt = "%8.8x "; break;
2308 case 2: value_fmt = "%4.4x "; break;
2309 case 1: value_fmt = "%2.2x "; break;
2310 default:
2311 /* "can't happen", caller checked */
2312 LOG_ERROR("invalid memory read size: %u", size);
2313 return;
2316 for (unsigned i = 0; i < count; i++)
2318 if (i % line_modulo == 0)
2320 output_len += snprintf(output + output_len,
2321 sizeof(output) - output_len,
2322 "0x%8.8x: ",
2323 (unsigned)(address + (i*size)));
2326 uint32_t value = 0;
2327 const uint8_t *value_ptr = buffer + i * size;
2328 switch (size) {
2329 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2330 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2331 case 1: value = *value_ptr;
2333 output_len += snprintf(output + output_len,
2334 sizeof(output) - output_len,
2335 value_fmt, value);
2337 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2339 command_print(cmd_ctx, "%s", output);
2340 output_len = 0;
2345 COMMAND_HANDLER(handle_md_command)
2347 if (CMD_ARGC < 1)
2348 return ERROR_COMMAND_SYNTAX_ERROR;
2350 unsigned size = 0;
2351 switch (CMD_NAME[2]) {
2352 case 'w': size = 4; break;
2353 case 'h': size = 2; break;
2354 case 'b': size = 1; break;
2355 default: return ERROR_COMMAND_SYNTAX_ERROR;
2358 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2359 int (*fn)(struct target *target,
2360 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2361 if (physical)
2363 CMD_ARGC--;
2364 CMD_ARGV++;
2365 fn=target_read_phys_memory;
2366 } else
2368 fn=target_read_memory;
2370 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2372 return ERROR_COMMAND_SYNTAX_ERROR;
2375 uint32_t address;
2376 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2378 unsigned count = 1;
2379 if (CMD_ARGC == 2)
2380 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2382 uint8_t *buffer = calloc(count, size);
2384 struct target *target = get_current_target(CMD_CTX);
2385 int retval = fn(target, address, size, count, buffer);
2386 if (ERROR_OK == retval)
2387 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2389 free(buffer);
2391 return retval;
2394 typedef int (*target_write_fn)(struct target *target,
2395 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2397 static int target_write_memory_fast(struct target *target,
2398 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2400 return target_write_buffer(target, address, size * count, buffer);
2403 static int target_fill_mem(struct target *target,
2404 uint32_t address,
2405 target_write_fn fn,
2406 unsigned data_size,
2407 /* value */
2408 uint32_t b,
2409 /* count */
2410 unsigned c)
2412 /* We have to write in reasonably large chunks to be able
2413 * to fill large memory areas with any sane speed */
2414 const unsigned chunk_size = 16384;
2415 uint8_t *target_buf = malloc(chunk_size * data_size);
2416 if (target_buf == NULL)
2418 LOG_ERROR("Out of memory");
2419 return ERROR_FAIL;
2422 for (unsigned i = 0; i < chunk_size; i ++)
2424 switch (data_size)
2426 case 4:
2427 target_buffer_set_u32(target, target_buf + i*data_size, b);
2428 break;
2429 case 2:
2430 target_buffer_set_u16(target, target_buf + i*data_size, b);
2431 break;
2432 case 1:
2433 target_buffer_set_u8(target, target_buf + i*data_size, b);
2434 break;
2435 default:
2436 exit(-1);
2440 int retval = ERROR_OK;
2442 for (unsigned x = 0; x < c; x += chunk_size)
2444 unsigned current;
2445 current = c - x;
2446 if (current > chunk_size)
2448 current = chunk_size;
2450 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2451 if (retval != ERROR_OK)
2453 break;
2455 /* avoid GDB timeouts */
2456 keep_alive();
2458 free(target_buf);
2460 return retval;
2464 COMMAND_HANDLER(handle_mw_command)
2466 if (CMD_ARGC < 2)
2468 return ERROR_COMMAND_SYNTAX_ERROR;
2470 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2471 target_write_fn fn;
2472 if (physical)
2474 CMD_ARGC--;
2475 CMD_ARGV++;
2476 fn=target_write_phys_memory;
2477 } else
2479 fn = target_write_memory_fast;
2481 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2482 return ERROR_COMMAND_SYNTAX_ERROR;
2484 uint32_t address;
2485 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2487 uint32_t value;
2488 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2490 unsigned count = 1;
2491 if (CMD_ARGC == 3)
2492 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2494 struct target *target = get_current_target(CMD_CTX);
2495 unsigned wordsize;
2496 switch (CMD_NAME[2])
2498 case 'w':
2499 wordsize = 4;
2500 break;
2501 case 'h':
2502 wordsize = 2;
2503 break;
2504 case 'b':
2505 wordsize = 1;
2506 break;
2507 default:
2508 return ERROR_COMMAND_SYNTAX_ERROR;
2511 return target_fill_mem(target, address, fn, wordsize, value, count);
2514 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2515 uint32_t *min_address, uint32_t *max_address)
2517 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2518 return ERROR_COMMAND_SYNTAX_ERROR;
2520 /* a base address isn't always necessary,
2521 * default to 0x0 (i.e. don't relocate) */
2522 if (CMD_ARGC >= 2)
2524 uint32_t addr;
2525 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2526 image->base_address = addr;
2527 image->base_address_set = 1;
2529 else
2530 image->base_address_set = 0;
2532 image->start_address_set = 0;
2534 if (CMD_ARGC >= 4)
2536 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2538 if (CMD_ARGC == 5)
2540 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2541 // use size (given) to find max (required)
2542 *max_address += *min_address;
2545 if (*min_address > *max_address)
2546 return ERROR_COMMAND_SYNTAX_ERROR;
2548 return ERROR_OK;
2551 COMMAND_HANDLER(handle_load_image_command)
2553 uint8_t *buffer;
2554 size_t buf_cnt;
2555 uint32_t image_size;
2556 uint32_t min_address = 0;
2557 uint32_t max_address = 0xffffffff;
2558 int i;
2559 struct image image;
2561 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2562 &image, &min_address, &max_address);
2563 if (ERROR_OK != retval)
2564 return retval;
2566 struct target *target = get_current_target(CMD_CTX);
2568 struct duration bench;
2569 duration_start(&bench);
2571 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2573 return ERROR_OK;
2576 image_size = 0x0;
2577 retval = ERROR_OK;
2578 for (i = 0; i < image.num_sections; i++)
2580 buffer = malloc(image.sections[i].size);
2581 if (buffer == NULL)
2583 command_print(CMD_CTX,
2584 "error allocating buffer for section (%d bytes)",
2585 (int)(image.sections[i].size));
2586 break;
2589 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2591 free(buffer);
2592 break;
2595 uint32_t offset = 0;
2596 uint32_t length = buf_cnt;
2598 /* DANGER!!! beware of unsigned comparision here!!! */
2600 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2601 (image.sections[i].base_address < max_address))
2603 if (image.sections[i].base_address < min_address)
2605 /* clip addresses below */
2606 offset += min_address-image.sections[i].base_address;
2607 length -= offset;
2610 if (image.sections[i].base_address + buf_cnt > max_address)
2612 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2615 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2617 free(buffer);
2618 break;
2620 image_size += length;
2621 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2622 (unsigned int)length,
2623 image.sections[i].base_address + offset);
2626 free(buffer);
2629 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2631 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2632 "in %fs (%0.3f KiB/s)", image_size,
2633 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2636 image_close(&image);
2638 return retval;
2642 COMMAND_HANDLER(handle_dump_image_command)
2644 struct fileio fileio;
2645 uint8_t buffer[560];
2646 int retval, retvaltemp;
2647 uint32_t address, size;
2648 struct duration bench;
2649 struct target *target = get_current_target(CMD_CTX);
2651 if (CMD_ARGC != 3)
2652 return ERROR_COMMAND_SYNTAX_ERROR;
2654 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2655 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2657 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2658 if (retval != ERROR_OK)
2659 return retval;
2661 duration_start(&bench);
2663 retval = ERROR_OK;
2664 while (size > 0)
2666 size_t size_written;
2667 uint32_t this_run_size = (size > 560) ? 560 : size;
2668 retval = target_read_buffer(target, address, this_run_size, buffer);
2669 if (retval != ERROR_OK)
2671 break;
2674 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2675 if (retval != ERROR_OK)
2677 break;
2680 size -= this_run_size;
2681 address += this_run_size;
2684 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2686 int filesize;
2687 retval = fileio_size(&fileio, &filesize);
2688 if (retval != ERROR_OK)
2689 return retval;
2690 command_print(CMD_CTX,
2691 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2692 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2695 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2696 return retvaltemp;
2698 return retval;
2701 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2703 uint8_t *buffer;
2704 size_t buf_cnt;
2705 uint32_t image_size;
2706 int i;
2707 int retval;
2708 uint32_t checksum = 0;
2709 uint32_t mem_checksum = 0;
2711 struct image image;
2713 struct target *target = get_current_target(CMD_CTX);
2715 if (CMD_ARGC < 1)
2717 return ERROR_COMMAND_SYNTAX_ERROR;
2720 if (!target)
2722 LOG_ERROR("no target selected");
2723 return ERROR_FAIL;
2726 struct duration bench;
2727 duration_start(&bench);
2729 if (CMD_ARGC >= 2)
2731 uint32_t addr;
2732 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2733 image.base_address = addr;
2734 image.base_address_set = 1;
2736 else
2738 image.base_address_set = 0;
2739 image.base_address = 0x0;
2742 image.start_address_set = 0;
2744 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2746 return retval;
2749 image_size = 0x0;
2750 int diffs = 0;
2751 retval = ERROR_OK;
2752 for (i = 0; i < image.num_sections; i++)
2754 buffer = malloc(image.sections[i].size);
2755 if (buffer == NULL)
2757 command_print(CMD_CTX,
2758 "error allocating buffer for section (%d bytes)",
2759 (int)(image.sections[i].size));
2760 break;
2762 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2764 free(buffer);
2765 break;
2768 if (verify)
2770 /* calculate checksum of image */
2771 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2772 if (retval != ERROR_OK)
2774 free(buffer);
2775 break;
2778 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2779 if (retval != ERROR_OK)
2781 free(buffer);
2782 break;
2785 if (checksum != mem_checksum)
2787 /* failed crc checksum, fall back to a binary compare */
2788 uint8_t *data;
2790 if (diffs == 0)
2792 LOG_ERROR("checksum mismatch - attempting binary compare");
2795 data = (uint8_t*)malloc(buf_cnt);
2797 /* Can we use 32bit word accesses? */
2798 int size = 1;
2799 int count = buf_cnt;
2800 if ((count % 4) == 0)
2802 size *= 4;
2803 count /= 4;
2805 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2806 if (retval == ERROR_OK)
2808 uint32_t t;
2809 for (t = 0; t < buf_cnt; t++)
2811 if (data[t] != buffer[t])
2813 command_print(CMD_CTX,
2814 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2815 diffs,
2816 (unsigned)(t + image.sections[i].base_address),
2817 data[t],
2818 buffer[t]);
2819 if (diffs++ >= 127)
2821 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2822 free(data);
2823 free(buffer);
2824 goto done;
2827 keep_alive();
2830 free(data);
2832 } else
2834 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2835 image.sections[i].base_address,
2836 buf_cnt);
2839 free(buffer);
2840 image_size += buf_cnt;
2842 if (diffs > 0)
2844 command_print(CMD_CTX, "No more differences found.");
2846 done:
2847 if (diffs > 0)
2849 retval = ERROR_FAIL;
2851 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2853 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2854 "in %fs (%0.3f KiB/s)", image_size,
2855 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2858 image_close(&image);
2860 return retval;
2863 COMMAND_HANDLER(handle_verify_image_command)
2865 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2868 COMMAND_HANDLER(handle_test_image_command)
2870 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2873 static int handle_bp_command_list(struct command_context *cmd_ctx)
2875 struct target *target = get_current_target(cmd_ctx);
2876 struct breakpoint *breakpoint = target->breakpoints;
2877 while (breakpoint)
2879 if (breakpoint->type == BKPT_SOFT)
2881 char* buf = buf_to_str(breakpoint->orig_instr,
2882 breakpoint->length, 16);
2883 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2884 breakpoint->address,
2885 breakpoint->length,
2886 breakpoint->set, buf);
2887 free(buf);
2889 else
2891 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2892 breakpoint->address,
2893 breakpoint->length, breakpoint->set);
2896 breakpoint = breakpoint->next;
2898 return ERROR_OK;
2901 static int handle_bp_command_set(struct command_context *cmd_ctx,
2902 uint32_t addr, uint32_t length, int hw)
2904 struct target *target = get_current_target(cmd_ctx);
2905 int retval = breakpoint_add(target, addr, length, hw);
2906 if (ERROR_OK == retval)
2907 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2908 else
2909 LOG_ERROR("Failure setting breakpoint");
2910 return retval;
2913 COMMAND_HANDLER(handle_bp_command)
2915 if (CMD_ARGC == 0)
2916 return handle_bp_command_list(CMD_CTX);
2918 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2920 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2921 return ERROR_COMMAND_SYNTAX_ERROR;
2924 uint32_t addr;
2925 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2926 uint32_t length;
2927 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2929 int hw = BKPT_SOFT;
2930 if (CMD_ARGC == 3)
2932 if (strcmp(CMD_ARGV[2], "hw") == 0)
2933 hw = BKPT_HARD;
2934 else
2935 return ERROR_COMMAND_SYNTAX_ERROR;
2938 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2941 COMMAND_HANDLER(handle_rbp_command)
2943 if (CMD_ARGC != 1)
2944 return ERROR_COMMAND_SYNTAX_ERROR;
2946 uint32_t addr;
2947 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2949 struct target *target = get_current_target(CMD_CTX);
2950 breakpoint_remove(target, addr);
2952 return ERROR_OK;
2955 COMMAND_HANDLER(handle_wp_command)
2957 struct target *target = get_current_target(CMD_CTX);
2959 if (CMD_ARGC == 0)
2961 struct watchpoint *watchpoint = target->watchpoints;
2963 while (watchpoint)
2965 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2966 ", len: 0x%8.8" PRIx32
2967 ", r/w/a: %i, value: 0x%8.8" PRIx32
2968 ", mask: 0x%8.8" PRIx32,
2969 watchpoint->address,
2970 watchpoint->length,
2971 (int)watchpoint->rw,
2972 watchpoint->value,
2973 watchpoint->mask);
2974 watchpoint = watchpoint->next;
2976 return ERROR_OK;
2979 enum watchpoint_rw type = WPT_ACCESS;
2980 uint32_t addr = 0;
2981 uint32_t length = 0;
2982 uint32_t data_value = 0x0;
2983 uint32_t data_mask = 0xffffffff;
2985 switch (CMD_ARGC)
2987 case 5:
2988 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2989 // fall through
2990 case 4:
2991 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2992 // fall through
2993 case 3:
2994 switch (CMD_ARGV[2][0])
2996 case 'r':
2997 type = WPT_READ;
2998 break;
2999 case 'w':
3000 type = WPT_WRITE;
3001 break;
3002 case 'a':
3003 type = WPT_ACCESS;
3004 break;
3005 default:
3006 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3007 return ERROR_COMMAND_SYNTAX_ERROR;
3009 // fall through
3010 case 2:
3011 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3012 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3013 break;
3015 default:
3016 command_print(CMD_CTX, "usage: wp [address length "
3017 "[(r|w|a) [value [mask]]]]");
3018 return ERROR_COMMAND_SYNTAX_ERROR;
3021 int retval = watchpoint_add(target, addr, length, type,
3022 data_value, data_mask);
3023 if (ERROR_OK != retval)
3024 LOG_ERROR("Failure setting watchpoints");
3026 return retval;
3029 COMMAND_HANDLER(handle_rwp_command)
3031 if (CMD_ARGC != 1)
3032 return ERROR_COMMAND_SYNTAX_ERROR;
3034 uint32_t addr;
3035 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3037 struct target *target = get_current_target(CMD_CTX);
3038 watchpoint_remove(target, addr);
3040 return ERROR_OK;
3045 * Translate a virtual address to a physical address.
3047 * The low-level target implementation must have logged a detailed error
3048 * which is forwarded to telnet/GDB session.
3050 COMMAND_HANDLER(handle_virt2phys_command)
3052 if (CMD_ARGC != 1)
3053 return ERROR_COMMAND_SYNTAX_ERROR;
3055 uint32_t va;
3056 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3057 uint32_t pa;
3059 struct target *target = get_current_target(CMD_CTX);
3060 int retval = target->type->virt2phys(target, va, &pa);
3061 if (retval == ERROR_OK)
3062 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3064 return retval;
3067 static void writeData(FILE *f, const void *data, size_t len)
3069 size_t written = fwrite(data, 1, len, f);
3070 if (written != len)
3071 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3074 static void writeLong(FILE *f, int l)
3076 int i;
3077 for (i = 0; i < 4; i++)
3079 char c = (l >> (i*8))&0xff;
3080 writeData(f, &c, 1);
3085 static void writeString(FILE *f, char *s)
3087 writeData(f, s, strlen(s));
3090 /* Dump a gmon.out histogram file. */
3091 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3093 uint32_t i;
3094 FILE *f = fopen(filename, "w");
3095 if (f == NULL)
3096 return;
3097 writeString(f, "gmon");
3098 writeLong(f, 0x00000001); /* Version */
3099 writeLong(f, 0); /* padding */
3100 writeLong(f, 0); /* padding */
3101 writeLong(f, 0); /* padding */
3103 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3104 writeData(f, &zero, 1);
3106 /* figure out bucket size */
3107 uint32_t min = samples[0];
3108 uint32_t max = samples[0];
3109 for (i = 0; i < sampleNum; i++)
3111 if (min > samples[i])
3113 min = samples[i];
3115 if (max < samples[i])
3117 max = samples[i];
3121 int addressSpace = (max-min + 1);
3123 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3124 uint32_t length = addressSpace;
3125 if (length > maxBuckets)
3127 length = maxBuckets;
3129 int *buckets = malloc(sizeof(int)*length);
3130 if (buckets == NULL)
3132 fclose(f);
3133 return;
3135 memset(buckets, 0, sizeof(int)*length);
3136 for (i = 0; i < sampleNum;i++)
3138 uint32_t address = samples[i];
3139 long long a = address-min;
3140 long long b = length-1;
3141 long long c = addressSpace-1;
3142 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3143 buckets[index_t]++;
3146 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3147 writeLong(f, min); /* low_pc */
3148 writeLong(f, max); /* high_pc */
3149 writeLong(f, length); /* # of samples */
3150 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3151 writeString(f, "seconds");
3152 for (i = 0; i < (15-strlen("seconds")); i++)
3153 writeData(f, &zero, 1);
3154 writeString(f, "s");
3156 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3158 char *data = malloc(2*length);
3159 if (data != NULL)
3161 for (i = 0; i < length;i++)
3163 int val;
3164 val = buckets[i];
3165 if (val > 65535)
3167 val = 65535;
3169 data[i*2]=val&0xff;
3170 data[i*2 + 1]=(val >> 8)&0xff;
3172 free(buckets);
3173 writeData(f, data, length * 2);
3174 free(data);
3175 } else
3177 free(buckets);
3180 fclose(f);
3183 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3184 * which will be used as a random sampling of PC */
3185 COMMAND_HANDLER(handle_profile_command)
3187 struct target *target = get_current_target(CMD_CTX);
3188 struct timeval timeout, now;
3190 gettimeofday(&timeout, NULL);
3191 if (CMD_ARGC != 2)
3193 return ERROR_COMMAND_SYNTAX_ERROR;
3195 unsigned offset;
3196 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3198 timeval_add_time(&timeout, offset, 0);
3201 * @todo: Some cores let us sample the PC without the
3202 * annoying halt/resume step; for example, ARMv7 PCSR.
3203 * Provide a way to use that more efficient mechanism.
3206 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3208 static const int maxSample = 10000;
3209 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3210 if (samples == NULL)
3211 return ERROR_OK;
3213 int numSamples = 0;
3214 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3215 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3217 for (;;)
3219 int retval;
3220 target_poll(target);
3221 if (target->state == TARGET_HALTED)
3223 uint32_t t=*((uint32_t *)reg->value);
3224 samples[numSamples++]=t;
3225 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3226 target_poll(target);
3227 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3228 } else if (target->state == TARGET_RUNNING)
3230 /* We want to quickly sample the PC. */
3231 if ((retval = target_halt(target)) != ERROR_OK)
3233 free(samples);
3234 return retval;
3236 } else
3238 command_print(CMD_CTX, "Target not halted or running");
3239 retval = ERROR_OK;
3240 break;
3242 if (retval != ERROR_OK)
3244 break;
3247 gettimeofday(&now, NULL);
3248 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3250 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3251 if ((retval = target_poll(target)) != ERROR_OK)
3253 free(samples);
3254 return retval;
3256 if (target->state == TARGET_HALTED)
3258 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3260 if ((retval = target_poll(target)) != ERROR_OK)
3262 free(samples);
3263 return retval;
3265 writeGmon(samples, numSamples, CMD_ARGV[1]);
3266 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3267 break;
3270 free(samples);
3272 return ERROR_OK;
3275 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3277 char *namebuf;
3278 Jim_Obj *nameObjPtr, *valObjPtr;
3279 int result;
3281 namebuf = alloc_printf("%s(%d)", varname, idx);
3282 if (!namebuf)
3283 return JIM_ERR;
3285 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3286 valObjPtr = Jim_NewIntObj(interp, val);
3287 if (!nameObjPtr || !valObjPtr)
3289 free(namebuf);
3290 return JIM_ERR;
3293 Jim_IncrRefCount(nameObjPtr);
3294 Jim_IncrRefCount(valObjPtr);
3295 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3296 Jim_DecrRefCount(interp, nameObjPtr);
3297 Jim_DecrRefCount(interp, valObjPtr);
3298 free(namebuf);
3299 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3300 return result;
3303 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3305 struct command_context *context;
3306 struct target *target;
3308 context = current_command_context(interp);
3309 assert (context != NULL);
3311 target = get_current_target(context);
3312 if (target == NULL)
3314 LOG_ERROR("mem2array: no current target");
3315 return JIM_ERR;
3318 return target_mem2array(interp, target, argc-1, argv + 1);
3321 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3323 long l;
3324 uint32_t width;
3325 int len;
3326 uint32_t addr;
3327 uint32_t count;
3328 uint32_t v;
3329 const char *varname;
3330 int n, e, retval;
3331 uint32_t i;
3333 /* argv[1] = name of array to receive the data
3334 * argv[2] = desired width
3335 * argv[3] = memory address
3336 * argv[4] = count of times to read
3338 if (argc != 4) {
3339 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3340 return JIM_ERR;
3342 varname = Jim_GetString(argv[0], &len);
3343 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3345 e = Jim_GetLong(interp, argv[1], &l);
3346 width = l;
3347 if (e != JIM_OK) {
3348 return e;
3351 e = Jim_GetLong(interp, argv[2], &l);
3352 addr = l;
3353 if (e != JIM_OK) {
3354 return e;
3356 e = Jim_GetLong(interp, argv[3], &l);
3357 len = l;
3358 if (e != JIM_OK) {
3359 return e;
3361 switch (width) {
3362 case 8:
3363 width = 1;
3364 break;
3365 case 16:
3366 width = 2;
3367 break;
3368 case 32:
3369 width = 4;
3370 break;
3371 default:
3372 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3373 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3374 return JIM_ERR;
3376 if (len == 0) {
3377 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3378 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3379 return JIM_ERR;
3381 if ((addr + (len * width)) < addr) {
3382 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3383 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3384 return JIM_ERR;
3386 /* absurd transfer size? */
3387 if (len > 65536) {
3388 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3389 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3390 return JIM_ERR;
3393 if ((width == 1) ||
3394 ((width == 2) && ((addr & 1) == 0)) ||
3395 ((width == 4) && ((addr & 3) == 0))) {
3396 /* all is well */
3397 } else {
3398 char buf[100];
3399 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3400 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3401 addr,
3402 width);
3403 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3404 return JIM_ERR;
3407 /* Transfer loop */
3409 /* index counter */
3410 n = 0;
3412 size_t buffersize = 4096;
3413 uint8_t *buffer = malloc(buffersize);
3414 if (buffer == NULL)
3415 return JIM_ERR;
3417 /* assume ok */
3418 e = JIM_OK;
3419 while (len) {
3420 /* Slurp... in buffer size chunks */
3422 count = len; /* in objects.. */
3423 if (count > (buffersize/width)) {
3424 count = (buffersize/width);
3427 retval = target_read_memory(target, addr, width, count, buffer);
3428 if (retval != ERROR_OK) {
3429 /* BOO !*/
3430 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3431 (unsigned int)addr,
3432 (int)width,
3433 (int)count);
3434 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3435 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3436 e = JIM_ERR;
3437 len = 0;
3438 } else {
3439 v = 0; /* shut up gcc */
3440 for (i = 0 ;i < count ;i++, n++) {
3441 switch (width) {
3442 case 4:
3443 v = target_buffer_get_u32(target, &buffer[i*width]);
3444 break;
3445 case 2:
3446 v = target_buffer_get_u16(target, &buffer[i*width]);
3447 break;
3448 case 1:
3449 v = buffer[i] & 0x0ff;
3450 break;
3452 new_int_array_element(interp, varname, n, v);
3454 len -= count;
3458 free(buffer);
3460 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3462 return JIM_OK;
3465 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3467 char *namebuf;
3468 Jim_Obj *nameObjPtr, *valObjPtr;
3469 int result;
3470 long l;
3472 namebuf = alloc_printf("%s(%d)", varname, idx);
3473 if (!namebuf)
3474 return JIM_ERR;
3476 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3477 if (!nameObjPtr)
3479 free(namebuf);
3480 return JIM_ERR;
3483 Jim_IncrRefCount(nameObjPtr);
3484 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3485 Jim_DecrRefCount(interp, nameObjPtr);
3486 free(namebuf);
3487 if (valObjPtr == NULL)
3488 return JIM_ERR;
3490 result = Jim_GetLong(interp, valObjPtr, &l);
3491 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3492 *val = l;
3493 return result;
3496 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3498 struct command_context *context;
3499 struct target *target;
3501 context = current_command_context(interp);
3502 assert (context != NULL);
3504 target = get_current_target(context);
3505 if (target == NULL) {
3506 LOG_ERROR("array2mem: no current target");
3507 return JIM_ERR;
3510 return target_array2mem(interp,target, argc-1, argv + 1);
3513 static int target_array2mem(Jim_Interp *interp, struct target *target,
3514 int argc, Jim_Obj *const *argv)
3516 long l;
3517 uint32_t width;
3518 int len;
3519 uint32_t addr;
3520 uint32_t count;
3521 uint32_t v;
3522 const char *varname;
3523 int n, e, retval;
3524 uint32_t i;
3526 /* argv[1] = name of array to get the data
3527 * argv[2] = desired width
3528 * argv[3] = memory address
3529 * argv[4] = count to write
3531 if (argc != 4) {
3532 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3533 return JIM_ERR;
3535 varname = Jim_GetString(argv[0], &len);
3536 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3538 e = Jim_GetLong(interp, argv[1], &l);
3539 width = l;
3540 if (e != JIM_OK) {
3541 return e;
3544 e = Jim_GetLong(interp, argv[2], &l);
3545 addr = l;
3546 if (e != JIM_OK) {
3547 return e;
3549 e = Jim_GetLong(interp, argv[3], &l);
3550 len = l;
3551 if (e != JIM_OK) {
3552 return e;
3554 switch (width) {
3555 case 8:
3556 width = 1;
3557 break;
3558 case 16:
3559 width = 2;
3560 break;
3561 case 32:
3562 width = 4;
3563 break;
3564 default:
3565 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3566 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3567 return JIM_ERR;
3569 if (len == 0) {
3570 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3571 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3572 return JIM_ERR;
3574 if ((addr + (len * width)) < addr) {
3575 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3576 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3577 return JIM_ERR;
3579 /* absurd transfer size? */
3580 if (len > 65536) {
3581 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3582 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3583 return JIM_ERR;
3586 if ((width == 1) ||
3587 ((width == 2) && ((addr & 1) == 0)) ||
3588 ((width == 4) && ((addr & 3) == 0))) {
3589 /* all is well */
3590 } else {
3591 char buf[100];
3592 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3593 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3594 (unsigned int)addr,
3595 (int)width);
3596 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3597 return JIM_ERR;
3600 /* Transfer loop */
3602 /* index counter */
3603 n = 0;
3604 /* assume ok */
3605 e = JIM_OK;
3607 size_t buffersize = 4096;
3608 uint8_t *buffer = malloc(buffersize);
3609 if (buffer == NULL)
3610 return JIM_ERR;
3612 while (len) {
3613 /* Slurp... in buffer size chunks */
3615 count = len; /* in objects.. */
3616 if (count > (buffersize/width)) {
3617 count = (buffersize/width);
3620 v = 0; /* shut up gcc */
3621 for (i = 0 ;i < count ;i++, n++) {
3622 get_int_array_element(interp, varname, n, &v);
3623 switch (width) {
3624 case 4:
3625 target_buffer_set_u32(target, &buffer[i*width], v);
3626 break;
3627 case 2:
3628 target_buffer_set_u16(target, &buffer[i*width], v);
3629 break;
3630 case 1:
3631 buffer[i] = v & 0x0ff;
3632 break;
3635 len -= count;
3637 retval = target_write_memory(target, addr, width, count, buffer);
3638 if (retval != ERROR_OK) {
3639 /* BOO !*/
3640 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3641 (unsigned int)addr,
3642 (int)width,
3643 (int)count);
3644 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3645 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3646 e = JIM_ERR;
3647 len = 0;
3651 free(buffer);
3653 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3655 return JIM_OK;
3658 /* FIX? should we propagate errors here rather than printing them
3659 * and continuing?
3661 void target_handle_event(struct target *target, enum target_event e)
3663 struct target_event_action *teap;
3665 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3666 if (teap->event == e) {
3667 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3668 target->target_number,
3669 target_name(target),
3670 target_type_name(target),
3672 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3673 Jim_GetString(teap->body, NULL));
3674 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3676 Jim_MakeErrorMessage(teap->interp);
3677 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3684 * Returns true only if the target has a handler for the specified event.
3686 bool target_has_event_action(struct target *target, enum target_event event)
3688 struct target_event_action *teap;
3690 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3691 if (teap->event == event)
3692 return true;
3694 return false;
3697 enum target_cfg_param {
3698 TCFG_TYPE,
3699 TCFG_EVENT,
3700 TCFG_WORK_AREA_VIRT,
3701 TCFG_WORK_AREA_PHYS,
3702 TCFG_WORK_AREA_SIZE,
3703 TCFG_WORK_AREA_BACKUP,
3704 TCFG_ENDIAN,
3705 TCFG_VARIANT,
3706 TCFG_COREID,
3707 TCFG_CHAIN_POSITION,
3710 static Jim_Nvp nvp_config_opts[] = {
3711 { .name = "-type", .value = TCFG_TYPE },
3712 { .name = "-event", .value = TCFG_EVENT },
3713 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3714 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3715 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3716 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3717 { .name = "-endian" , .value = TCFG_ENDIAN },
3718 { .name = "-variant", .value = TCFG_VARIANT },
3719 { .name = "-coreid", .value = TCFG_COREID },
3720 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3721 { .name = NULL, .value = -1 }
3724 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3726 Jim_Nvp *n;
3727 Jim_Obj *o;
3728 jim_wide w;
3729 char *cp;
3730 int e;
3732 /* parse config or cget options ... */
3733 while (goi->argc > 0) {
3734 Jim_SetEmptyResult(goi->interp);
3735 /* Jim_GetOpt_Debug(goi); */
3737 if (target->type->target_jim_configure) {
3738 /* target defines a configure function */
3739 /* target gets first dibs on parameters */
3740 e = (*(target->type->target_jim_configure))(target, goi);
3741 if (e == JIM_OK) {
3742 /* more? */
3743 continue;
3745 if (e == JIM_ERR) {
3746 /* An error */
3747 return e;
3749 /* otherwise we 'continue' below */
3751 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3752 if (e != JIM_OK) {
3753 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3754 return e;
3756 switch (n->value) {
3757 case TCFG_TYPE:
3758 /* not setable */
3759 if (goi->isconfigure) {
3760 Jim_SetResultFormatted(goi->interp,
3761 "not settable: %s", n->name);
3762 return JIM_ERR;
3763 } else {
3764 no_params:
3765 if (goi->argc != 0) {
3766 Jim_WrongNumArgs(goi->interp,
3767 goi->argc, goi->argv,
3768 "NO PARAMS");
3769 return JIM_ERR;
3772 Jim_SetResultString(goi->interp,
3773 target_type_name(target), -1);
3774 /* loop for more */
3775 break;
3776 case TCFG_EVENT:
3777 if (goi->argc == 0) {
3778 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3779 return JIM_ERR;
3782 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3783 if (e != JIM_OK) {
3784 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3785 return e;
3788 if (goi->isconfigure) {
3789 if (goi->argc != 1) {
3790 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3791 return JIM_ERR;
3793 } else {
3794 if (goi->argc != 0) {
3795 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3796 return JIM_ERR;
3801 struct target_event_action *teap;
3803 teap = target->event_action;
3804 /* replace existing? */
3805 while (teap) {
3806 if (teap->event == (enum target_event)n->value) {
3807 break;
3809 teap = teap->next;
3812 if (goi->isconfigure) {
3813 bool replace = true;
3814 if (teap == NULL) {
3815 /* create new */
3816 teap = calloc(1, sizeof(*teap));
3817 replace = false;
3819 teap->event = n->value;
3820 teap->interp = goi->interp;
3821 Jim_GetOpt_Obj(goi, &o);
3822 if (teap->body) {
3823 Jim_DecrRefCount(teap->interp, teap->body);
3825 teap->body = Jim_DuplicateObj(goi->interp, o);
3827 * FIXME:
3828 * Tcl/TK - "tk events" have a nice feature.
3829 * See the "BIND" command.
3830 * We should support that here.
3831 * You can specify %X and %Y in the event code.
3832 * The idea is: %T - target name.
3833 * The idea is: %N - target number
3834 * The idea is: %E - event name.
3836 Jim_IncrRefCount(teap->body);
3838 if (!replace)
3840 /* add to head of event list */
3841 teap->next = target->event_action;
3842 target->event_action = teap;
3844 Jim_SetEmptyResult(goi->interp);
3845 } else {
3846 /* get */
3847 if (teap == NULL) {
3848 Jim_SetEmptyResult(goi->interp);
3849 } else {
3850 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3854 /* loop for more */
3855 break;
3857 case TCFG_WORK_AREA_VIRT:
3858 if (goi->isconfigure) {
3859 target_free_all_working_areas(target);
3860 e = Jim_GetOpt_Wide(goi, &w);
3861 if (e != JIM_OK) {
3862 return e;
3864 target->working_area_virt = w;
3865 target->working_area_virt_spec = true;
3866 } else {
3867 if (goi->argc != 0) {
3868 goto no_params;
3871 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3872 /* loop for more */
3873 break;
3875 case TCFG_WORK_AREA_PHYS:
3876 if (goi->isconfigure) {
3877 target_free_all_working_areas(target);
3878 e = Jim_GetOpt_Wide(goi, &w);
3879 if (e != JIM_OK) {
3880 return e;
3882 target->working_area_phys = w;
3883 target->working_area_phys_spec = true;
3884 } else {
3885 if (goi->argc != 0) {
3886 goto no_params;
3889 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3890 /* loop for more */
3891 break;
3893 case TCFG_WORK_AREA_SIZE:
3894 if (goi->isconfigure) {
3895 target_free_all_working_areas(target);
3896 e = Jim_GetOpt_Wide(goi, &w);
3897 if (e != JIM_OK) {
3898 return e;
3900 target->working_area_size = w;
3901 } else {
3902 if (goi->argc != 0) {
3903 goto no_params;
3906 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3907 /* loop for more */
3908 break;
3910 case TCFG_WORK_AREA_BACKUP:
3911 if (goi->isconfigure) {
3912 target_free_all_working_areas(target);
3913 e = Jim_GetOpt_Wide(goi, &w);
3914 if (e != JIM_OK) {
3915 return e;
3917 /* make this exactly 1 or 0 */
3918 target->backup_working_area = (!!w);
3919 } else {
3920 if (goi->argc != 0) {
3921 goto no_params;
3924 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3925 /* loop for more e*/
3926 break;
3928 case TCFG_ENDIAN:
3929 if (goi->isconfigure) {
3930 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3931 if (e != JIM_OK) {
3932 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3933 return e;
3935 target->endianness = n->value;
3936 } else {
3937 if (goi->argc != 0) {
3938 goto no_params;
3941 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3942 if (n->name == NULL) {
3943 target->endianness = TARGET_LITTLE_ENDIAN;
3944 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3946 Jim_SetResultString(goi->interp, n->name, -1);
3947 /* loop for more */
3948 break;
3950 case TCFG_VARIANT:
3951 if (goi->isconfigure) {
3952 if (goi->argc < 1) {
3953 Jim_SetResultFormatted(goi->interp,
3954 "%s ?STRING?",
3955 n->name);
3956 return JIM_ERR;
3958 if (target->variant) {
3959 free((void *)(target->variant));
3961 e = Jim_GetOpt_String(goi, &cp, NULL);
3962 target->variant = strdup(cp);
3963 } else {
3964 if (goi->argc != 0) {
3965 goto no_params;
3968 Jim_SetResultString(goi->interp, target->variant,-1);
3969 /* loop for more */
3970 break;
3972 case TCFG_COREID:
3973 if (goi->isconfigure) {
3974 e = Jim_GetOpt_Wide(goi, &w);
3975 if (e != JIM_OK) {
3976 return e;
3978 target->coreid = (int)w;
3979 } else {
3980 if (goi->argc != 0) {
3981 goto no_params;
3984 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3985 /* loop for more */
3986 break;
3988 case TCFG_CHAIN_POSITION:
3989 if (goi->isconfigure) {
3990 Jim_Obj *o_t;
3991 struct jtag_tap *tap;
3992 target_free_all_working_areas(target);
3993 e = Jim_GetOpt_Obj(goi, &o_t);
3994 if (e != JIM_OK) {
3995 return e;
3997 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
3998 if (tap == NULL) {
3999 return JIM_ERR;
4001 /* make this exactly 1 or 0 */
4002 target->tap = tap;
4003 } else {
4004 if (goi->argc != 0) {
4005 goto no_params;
4008 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4009 /* loop for more e*/
4010 break;
4012 } /* while (goi->argc) */
4015 /* done - we return */
4016 return JIM_OK;
4019 static int
4020 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4022 Jim_GetOptInfo goi;
4024 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4025 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4026 int need_args = 1 + goi.isconfigure;
4027 if (goi.argc < need_args)
4029 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4030 goi.isconfigure
4031 ? "missing: -option VALUE ..."
4032 : "missing: -option ...");
4033 return JIM_ERR;
4035 struct target *target = Jim_CmdPrivData(goi.interp);
4036 return target_configure(&goi, target);
4039 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4041 const char *cmd_name = Jim_GetString(argv[0], NULL);
4043 Jim_GetOptInfo goi;
4044 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4046 if (goi.argc < 2 || goi.argc > 4)
4048 Jim_SetResultFormatted(goi.interp,
4049 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4050 return JIM_ERR;
4053 target_write_fn fn;
4054 fn = target_write_memory_fast;
4056 int e;
4057 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4059 /* consume it */
4060 struct Jim_Obj *obj;
4061 e = Jim_GetOpt_Obj(&goi, &obj);
4062 if (e != JIM_OK)
4063 return e;
4065 fn = target_write_phys_memory;
4068 jim_wide a;
4069 e = Jim_GetOpt_Wide(&goi, &a);
4070 if (e != JIM_OK)
4071 return e;
4073 jim_wide b;
4074 e = Jim_GetOpt_Wide(&goi, &b);
4075 if (e != JIM_OK)
4076 return e;
4078 jim_wide c = 1;
4079 if (goi.argc == 1)
4081 e = Jim_GetOpt_Wide(&goi, &c);
4082 if (e != JIM_OK)
4083 return e;
4086 /* all args must be consumed */
4087 if (goi.argc != 0)
4089 return JIM_ERR;
4092 struct target *target = Jim_CmdPrivData(goi.interp);
4093 unsigned data_size;
4094 if (strcasecmp(cmd_name, "mww") == 0) {
4095 data_size = 4;
4097 else if (strcasecmp(cmd_name, "mwh") == 0) {
4098 data_size = 2;
4100 else if (strcasecmp(cmd_name, "mwb") == 0) {
4101 data_size = 1;
4102 } else {
4103 LOG_ERROR("command '%s' unknown: ", cmd_name);
4104 return JIM_ERR;
4107 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4110 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4112 const char *cmd_name = Jim_GetString(argv[0], NULL);
4114 Jim_GetOptInfo goi;
4115 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4117 if ((goi.argc < 1) || (goi.argc > 3))
4119 Jim_SetResultFormatted(goi.interp,
4120 "usage: %s [phys] <address> [<count>]", cmd_name);
4121 return JIM_ERR;
4124 int (*fn)(struct target *target,
4125 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4126 fn=target_read_memory;
4128 int e;
4129 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4131 /* consume it */
4132 struct Jim_Obj *obj;
4133 e = Jim_GetOpt_Obj(&goi, &obj);
4134 if (e != JIM_OK)
4135 return e;
4137 fn=target_read_phys_memory;
4140 jim_wide a;
4141 e = Jim_GetOpt_Wide(&goi, &a);
4142 if (e != JIM_OK) {
4143 return JIM_ERR;
4145 jim_wide c;
4146 if (goi.argc == 1) {
4147 e = Jim_GetOpt_Wide(&goi, &c);
4148 if (e != JIM_OK) {
4149 return JIM_ERR;
4151 } else {
4152 c = 1;
4155 /* all args must be consumed */
4156 if (goi.argc != 0)
4158 return JIM_ERR;
4161 jim_wide b = 1; /* shut up gcc */
4162 if (strcasecmp(cmd_name, "mdw") == 0)
4163 b = 4;
4164 else if (strcasecmp(cmd_name, "mdh") == 0)
4165 b = 2;
4166 else if (strcasecmp(cmd_name, "mdb") == 0)
4167 b = 1;
4168 else {
4169 LOG_ERROR("command '%s' unknown: ", cmd_name);
4170 return JIM_ERR;
4173 /* convert count to "bytes" */
4174 c = c * b;
4176 struct target *target = Jim_CmdPrivData(goi.interp);
4177 uint8_t target_buf[32];
4178 jim_wide x, y, z;
4179 while (c > 0) {
4180 y = c;
4181 if (y > 16) {
4182 y = 16;
4184 e = fn(target, a, b, y / b, target_buf);
4185 if (e != ERROR_OK) {
4186 char tmp[10];
4187 snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4188 Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4189 return JIM_ERR;
4192 command_print(NULL, "0x%08x ", (int)(a));
4193 switch (b) {
4194 case 4:
4195 for (x = 0; x < 16 && x < y; x += 4)
4197 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4198 command_print(NULL, "%08x ", (int)(z));
4200 for (; (x < 16) ; x += 4) {
4201 command_print(NULL, " ");
4203 break;
4204 case 2:
4205 for (x = 0; x < 16 && x < y; x += 2)
4207 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4208 command_print(NULL, "%04x ", (int)(z));
4210 for (; (x < 16) ; x += 2) {
4211 command_print(NULL, " ");
4213 break;
4214 case 1:
4215 default:
4216 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4217 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4218 command_print(NULL, "%02x ", (int)(z));
4220 for (; (x < 16) ; x += 1) {
4221 command_print(NULL, " ");
4223 break;
4225 /* ascii-ify the bytes */
4226 for (x = 0 ; x < y ; x++) {
4227 if ((target_buf[x] >= 0x20) &&
4228 (target_buf[x] <= 0x7e)) {
4229 /* good */
4230 } else {
4231 /* smack it */
4232 target_buf[x] = '.';
4235 /* space pad */
4236 while (x < 16) {
4237 target_buf[x] = ' ';
4238 x++;
4240 /* terminate */
4241 target_buf[16] = 0;
4242 /* print - with a newline */
4243 command_print(NULL, "%s\n", target_buf);
4244 /* NEXT... */
4245 c -= 16;
4246 a += 16;
4248 return JIM_OK;
4251 static int jim_target_mem2array(Jim_Interp *interp,
4252 int argc, Jim_Obj *const *argv)
4254 struct target *target = Jim_CmdPrivData(interp);
4255 return target_mem2array(interp, target, argc - 1, argv + 1);
4258 static int jim_target_array2mem(Jim_Interp *interp,
4259 int argc, Jim_Obj *const *argv)
4261 struct target *target = Jim_CmdPrivData(interp);
4262 return target_array2mem(interp, target, argc - 1, argv + 1);
4265 static int jim_target_tap_disabled(Jim_Interp *interp)
4267 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4268 return JIM_ERR;
4271 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4273 if (argc != 1)
4275 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4276 return JIM_ERR;
4278 struct target *target = Jim_CmdPrivData(interp);
4279 if (!target->tap->enabled)
4280 return jim_target_tap_disabled(interp);
4282 int e = target->type->examine(target);
4283 if (e != ERROR_OK)
4285 return JIM_ERR;
4287 return JIM_OK;
4290 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4292 if (argc != 1)
4294 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4295 return JIM_ERR;
4297 struct target *target = Jim_CmdPrivData(interp);
4299 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4300 return JIM_ERR;
4302 return JIM_OK;
4305 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4307 if (argc != 1)
4309 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4310 return JIM_ERR;
4312 struct target *target = Jim_CmdPrivData(interp);
4313 if (!target->tap->enabled)
4314 return jim_target_tap_disabled(interp);
4316 int e;
4317 if (!(target_was_examined(target))) {
4318 e = ERROR_TARGET_NOT_EXAMINED;
4319 } else {
4320 e = target->type->poll(target);
4322 if (e != ERROR_OK)
4324 return JIM_ERR;
4326 return JIM_OK;
4329 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4331 Jim_GetOptInfo goi;
4332 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4334 if (goi.argc != 2)
4336 Jim_WrongNumArgs(interp, 0, argv,
4337 "([tT]|[fF]|assert|deassert) BOOL");
4338 return JIM_ERR;
4341 Jim_Nvp *n;
4342 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4343 if (e != JIM_OK)
4345 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4346 return e;
4348 /* the halt or not param */
4349 jim_wide a;
4350 e = Jim_GetOpt_Wide(&goi, &a);
4351 if (e != JIM_OK)
4352 return e;
4354 struct target *target = Jim_CmdPrivData(goi.interp);
4355 if (!target->tap->enabled)
4356 return jim_target_tap_disabled(interp);
4357 if (!(target_was_examined(target)))
4359 LOG_ERROR("Target not examined yet");
4360 return ERROR_TARGET_NOT_EXAMINED;
4362 if (!target->type->assert_reset || !target->type->deassert_reset)
4364 Jim_SetResultFormatted(interp,
4365 "No target-specific reset for %s",
4366 target_name(target));
4367 return JIM_ERR;
4369 /* determine if we should halt or not. */
4370 target->reset_halt = !!a;
4371 /* When this happens - all workareas are invalid. */
4372 target_free_all_working_areas_restore(target, 0);
4374 /* do the assert */
4375 if (n->value == NVP_ASSERT) {
4376 e = target->type->assert_reset(target);
4377 } else {
4378 e = target->type->deassert_reset(target);
4380 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4383 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4385 if (argc != 1) {
4386 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4387 return JIM_ERR;
4389 struct target *target = Jim_CmdPrivData(interp);
4390 if (!target->tap->enabled)
4391 return jim_target_tap_disabled(interp);
4392 int e = target->type->halt(target);
4393 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4396 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4398 Jim_GetOptInfo goi;
4399 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4401 /* params: <name> statename timeoutmsecs */
4402 if (goi.argc != 2)
4404 const char *cmd_name = Jim_GetString(argv[0], NULL);
4405 Jim_SetResultFormatted(goi.interp,
4406 "%s <state_name> <timeout_in_msec>", cmd_name);
4407 return JIM_ERR;
4410 Jim_Nvp *n;
4411 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4412 if (e != JIM_OK) {
4413 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4414 return e;
4416 jim_wide a;
4417 e = Jim_GetOpt_Wide(&goi, &a);
4418 if (e != JIM_OK) {
4419 return e;
4421 struct target *target = Jim_CmdPrivData(interp);
4422 if (!target->tap->enabled)
4423 return jim_target_tap_disabled(interp);
4425 e = target_wait_state(target, n->value, a);
4426 if (e != ERROR_OK)
4428 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4429 Jim_SetResultFormatted(goi.interp,
4430 "target: %s wait %s fails (%#s) %s",
4431 target_name(target), n->name,
4432 eObj, target_strerror_safe(e));
4433 Jim_FreeNewObj(interp, eObj);
4434 return JIM_ERR;
4436 return JIM_OK;
4438 /* List for human, Events defined for this target.
4439 * scripts/programs should use 'name cget -event NAME'
4441 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4443 struct command_context *cmd_ctx = current_command_context(interp);
4444 assert (cmd_ctx != NULL);
4446 struct target *target = Jim_CmdPrivData(interp);
4447 struct target_event_action *teap = target->event_action;
4448 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4449 target->target_number,
4450 target_name(target));
4451 command_print(cmd_ctx, "%-25s | Body", "Event");
4452 command_print(cmd_ctx, "------------------------- | "
4453 "----------------------------------------");
4454 while (teap)
4456 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4457 command_print(cmd_ctx, "%-25s | %s",
4458 opt->name, Jim_GetString(teap->body, NULL));
4459 teap = teap->next;
4461 command_print(cmd_ctx, "***END***");
4462 return JIM_OK;
4464 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4466 if (argc != 1)
4468 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4469 return JIM_ERR;
4471 struct target *target = Jim_CmdPrivData(interp);
4472 Jim_SetResultString(interp, target_state_name(target), -1);
4473 return JIM_OK;
4475 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4477 Jim_GetOptInfo goi;
4478 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4479 if (goi.argc != 1)
4481 const char *cmd_name = Jim_GetString(argv[0], NULL);
4482 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4483 return JIM_ERR;
4485 Jim_Nvp *n;
4486 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4487 if (e != JIM_OK)
4489 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4490 return e;
4492 struct target *target = Jim_CmdPrivData(interp);
4493 target_handle_event(target, n->value);
4494 return JIM_OK;
4497 static const struct command_registration target_instance_command_handlers[] = {
4499 .name = "configure",
4500 .mode = COMMAND_CONFIG,
4501 .jim_handler = jim_target_configure,
4502 .help = "configure a new target for use",
4503 .usage = "[target_attribute ...]",
4506 .name = "cget",
4507 .mode = COMMAND_ANY,
4508 .jim_handler = jim_target_configure,
4509 .help = "returns the specified target attribute",
4510 .usage = "target_attribute",
4513 .name = "mww",
4514 .mode = COMMAND_EXEC,
4515 .jim_handler = jim_target_mw,
4516 .help = "Write 32-bit word(s) to target memory",
4517 .usage = "address data [count]",
4520 .name = "mwh",
4521 .mode = COMMAND_EXEC,
4522 .jim_handler = jim_target_mw,
4523 .help = "Write 16-bit half-word(s) to target memory",
4524 .usage = "address data [count]",
4527 .name = "mwb",
4528 .mode = COMMAND_EXEC,
4529 .jim_handler = jim_target_mw,
4530 .help = "Write byte(s) to target memory",
4531 .usage = "address data [count]",
4534 .name = "mdw",
4535 .mode = COMMAND_EXEC,
4536 .jim_handler = jim_target_md,
4537 .help = "Display target memory as 32-bit words",
4538 .usage = "address [count]",
4541 .name = "mdh",
4542 .mode = COMMAND_EXEC,
4543 .jim_handler = jim_target_md,
4544 .help = "Display target memory as 16-bit half-words",
4545 .usage = "address [count]",
4548 .name = "mdb",
4549 .mode = COMMAND_EXEC,
4550 .jim_handler = jim_target_md,
4551 .help = "Display target memory as 8-bit bytes",
4552 .usage = "address [count]",
4555 .name = "array2mem",
4556 .mode = COMMAND_EXEC,
4557 .jim_handler = jim_target_array2mem,
4558 .help = "Writes Tcl array of 8/16/32 bit numbers "
4559 "to target memory",
4560 .usage = "arrayname bitwidth address count",
4563 .name = "mem2array",
4564 .mode = COMMAND_EXEC,
4565 .jim_handler = jim_target_mem2array,
4566 .help = "Loads Tcl array of 8/16/32 bit numbers "
4567 "from target memory",
4568 .usage = "arrayname bitwidth address count",
4571 .name = "eventlist",
4572 .mode = COMMAND_EXEC,
4573 .jim_handler = jim_target_event_list,
4574 .help = "displays a table of events defined for this target",
4577 .name = "curstate",
4578 .mode = COMMAND_EXEC,
4579 .jim_handler = jim_target_current_state,
4580 .help = "displays the current state of this target",
4583 .name = "arp_examine",
4584 .mode = COMMAND_EXEC,
4585 .jim_handler = jim_target_examine,
4586 .help = "used internally for reset processing",
4589 .name = "arp_halt_gdb",
4590 .mode = COMMAND_EXEC,
4591 .jim_handler = jim_target_halt_gdb,
4592 .help = "used internally for reset processing to halt GDB",
4595 .name = "arp_poll",
4596 .mode = COMMAND_EXEC,
4597 .jim_handler = jim_target_poll,
4598 .help = "used internally for reset processing",
4601 .name = "arp_reset",
4602 .mode = COMMAND_EXEC,
4603 .jim_handler = jim_target_reset,
4604 .help = "used internally for reset processing",
4607 .name = "arp_halt",
4608 .mode = COMMAND_EXEC,
4609 .jim_handler = jim_target_halt,
4610 .help = "used internally for reset processing",
4613 .name = "arp_waitstate",
4614 .mode = COMMAND_EXEC,
4615 .jim_handler = jim_target_wait_state,
4616 .help = "used internally for reset processing",
4619 .name = "invoke-event",
4620 .mode = COMMAND_EXEC,
4621 .jim_handler = jim_target_invoke_event,
4622 .help = "invoke handler for specified event",
4623 .usage = "event_name",
4625 COMMAND_REGISTRATION_DONE
4628 static int target_create(Jim_GetOptInfo *goi)
4630 Jim_Obj *new_cmd;
4631 Jim_Cmd *cmd;
4632 const char *cp;
4633 char *cp2;
4634 int e;
4635 int x;
4636 struct target *target;
4637 struct command_context *cmd_ctx;
4639 cmd_ctx = current_command_context(goi->interp);
4640 assert (cmd_ctx != NULL);
4642 if (goi->argc < 3) {
4643 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4644 return JIM_ERR;
4647 /* COMMAND */
4648 Jim_GetOpt_Obj(goi, &new_cmd);
4649 /* does this command exist? */
4650 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4651 if (cmd) {
4652 cp = Jim_GetString(new_cmd, NULL);
4653 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4654 return JIM_ERR;
4657 /* TYPE */
4658 e = Jim_GetOpt_String(goi, &cp2, NULL);
4659 cp = cp2;
4660 /* now does target type exist */
4661 for (x = 0 ; target_types[x] ; x++) {
4662 if (0 == strcmp(cp, target_types[x]->name)) {
4663 /* found */
4664 break;
4667 if (target_types[x] == NULL) {
4668 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4669 for (x = 0 ; target_types[x] ; x++) {
4670 if (target_types[x + 1]) {
4671 Jim_AppendStrings(goi->interp,
4672 Jim_GetResult(goi->interp),
4673 target_types[x]->name,
4674 ", ", NULL);
4675 } else {
4676 Jim_AppendStrings(goi->interp,
4677 Jim_GetResult(goi->interp),
4678 " or ",
4679 target_types[x]->name,NULL);
4682 return JIM_ERR;
4685 /* Create it */
4686 target = calloc(1,sizeof(struct target));
4687 /* set target number */
4688 target->target_number = new_target_number();
4690 /* allocate memory for each unique target type */
4691 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4693 memcpy(target->type, target_types[x], sizeof(struct target_type));
4695 /* will be set by "-endian" */
4696 target->endianness = TARGET_ENDIAN_UNKNOWN;
4698 /* default to first core, override with -coreid */
4699 target->coreid = 0;
4701 target->working_area = 0x0;
4702 target->working_area_size = 0x0;
4703 target->working_areas = NULL;
4704 target->backup_working_area = 0;
4706 target->state = TARGET_UNKNOWN;
4707 target->debug_reason = DBG_REASON_UNDEFINED;
4708 target->reg_cache = NULL;
4709 target->breakpoints = NULL;
4710 target->watchpoints = NULL;
4711 target->next = NULL;
4712 target->arch_info = NULL;
4714 target->display = 1;
4716 target->halt_issued = false;
4718 /* initialize trace information */
4719 target->trace_info = malloc(sizeof(struct trace));
4720 target->trace_info->num_trace_points = 0;
4721 target->trace_info->trace_points_size = 0;
4722 target->trace_info->trace_points = NULL;
4723 target->trace_info->trace_history_size = 0;
4724 target->trace_info->trace_history = NULL;
4725 target->trace_info->trace_history_pos = 0;
4726 target->trace_info->trace_history_overflowed = 0;
4728 target->dbgmsg = NULL;
4729 target->dbg_msg_enabled = 0;
4731 target->endianness = TARGET_ENDIAN_UNKNOWN;
4733 /* Do the rest as "configure" options */
4734 goi->isconfigure = 1;
4735 e = target_configure(goi, target);
4737 if (target->tap == NULL)
4739 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4740 e = JIM_ERR;
4743 if (e != JIM_OK) {
4744 free(target->type);
4745 free(target);
4746 return e;
4749 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4750 /* default endian to little if not specified */
4751 target->endianness = TARGET_LITTLE_ENDIAN;
4754 /* incase variant is not set */
4755 if (!target->variant)
4756 target->variant = strdup("");
4758 cp = Jim_GetString(new_cmd, NULL);
4759 target->cmd_name = strdup(cp);
4761 /* create the target specific commands */
4762 if (target->type->commands) {
4763 e = register_commands(cmd_ctx, NULL, target->type->commands);
4764 if (ERROR_OK != e)
4765 LOG_ERROR("unable to register '%s' commands", cp);
4767 if (target->type->target_create) {
4768 (*(target->type->target_create))(target, goi->interp);
4771 /* append to end of list */
4773 struct target **tpp;
4774 tpp = &(all_targets);
4775 while (*tpp) {
4776 tpp = &((*tpp)->next);
4778 *tpp = target;
4781 /* now - create the new target name command */
4782 const const struct command_registration target_subcommands[] = {
4784 .chain = target_instance_command_handlers,
4787 .chain = target->type->commands,
4789 COMMAND_REGISTRATION_DONE
4791 const const struct command_registration target_commands[] = {
4793 .name = cp,
4794 .mode = COMMAND_ANY,
4795 .help = "target command group",
4796 .chain = target_subcommands,
4798 COMMAND_REGISTRATION_DONE
4800 e = register_commands(cmd_ctx, NULL, target_commands);
4801 if (ERROR_OK != e)
4802 return JIM_ERR;
4804 struct command *c = command_find_in_context(cmd_ctx, cp);
4805 assert(c);
4806 command_set_handler_data(c, target);
4808 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4811 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4813 if (argc != 1)
4815 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4816 return JIM_ERR;
4818 struct command_context *cmd_ctx = current_command_context(interp);
4819 assert (cmd_ctx != NULL);
4821 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4822 return JIM_OK;
4825 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4827 if (argc != 1)
4829 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4830 return JIM_ERR;
4832 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4833 for (unsigned x = 0; NULL != target_types[x]; x++)
4835 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4836 Jim_NewStringObj(interp, target_types[x]->name, -1));
4838 return JIM_OK;
4841 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4843 if (argc != 1)
4845 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4846 return JIM_ERR;
4848 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4849 struct target *target = all_targets;
4850 while (target)
4852 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4853 Jim_NewStringObj(interp, target_name(target), -1));
4854 target = target->next;
4856 return JIM_OK;
4859 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4861 Jim_GetOptInfo goi;
4862 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4863 if (goi.argc < 3)
4865 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4866 "<name> <target_type> [<target_options> ...]");
4867 return JIM_ERR;
4869 return target_create(&goi);
4872 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4874 Jim_GetOptInfo goi;
4875 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4877 /* It's OK to remove this mechanism sometime after August 2010 or so */
4878 LOG_WARNING("don't use numbers as target identifiers; use names");
4879 if (goi.argc != 1)
4881 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
4882 return JIM_ERR;
4884 jim_wide w;
4885 int e = Jim_GetOpt_Wide(&goi, &w);
4886 if (e != JIM_OK)
4887 return JIM_ERR;
4889 struct target *target;
4890 for (target = all_targets; NULL != target; target = target->next)
4892 if (target->target_number != w)
4893 continue;
4895 Jim_SetResultString(goi.interp, target_name(target), -1);
4896 return JIM_OK;
4899 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
4900 Jim_SetResultFormatted(goi.interp,
4901 "Target: number %#s does not exist", wObj);
4902 Jim_FreeNewObj(interp, wObj);
4904 return JIM_ERR;
4907 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4909 if (argc != 1)
4911 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4912 return JIM_ERR;
4914 unsigned count = 0;
4915 struct target *target = all_targets;
4916 while (NULL != target)
4918 target = target->next;
4919 count++;
4921 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4922 return JIM_OK;
4925 static const struct command_registration target_subcommand_handlers[] = {
4927 .name = "init",
4928 .mode = COMMAND_CONFIG,
4929 .handler = handle_target_init_command,
4930 .help = "initialize targets",
4933 .name = "create",
4934 /* REVISIT this should be COMMAND_CONFIG ... */
4935 .mode = COMMAND_ANY,
4936 .jim_handler = jim_target_create,
4937 .usage = "name type '-chain-position' name [options ...]",
4938 .help = "Creates and selects a new target",
4941 .name = "current",
4942 .mode = COMMAND_ANY,
4943 .jim_handler = jim_target_current,
4944 .help = "Returns the currently selected target",
4947 .name = "types",
4948 .mode = COMMAND_ANY,
4949 .jim_handler = jim_target_types,
4950 .help = "Returns the available target types as "
4951 "a list of strings",
4954 .name = "names",
4955 .mode = COMMAND_ANY,
4956 .jim_handler = jim_target_names,
4957 .help = "Returns the names of all targets as a list of strings",
4960 .name = "number",
4961 .mode = COMMAND_ANY,
4962 .jim_handler = jim_target_number,
4963 .usage = "number",
4964 .help = "Returns the name of the numbered target "
4965 "(DEPRECATED)",
4968 .name = "count",
4969 .mode = COMMAND_ANY,
4970 .jim_handler = jim_target_count,
4971 .help = "Returns the number of targets as an integer "
4972 "(DEPRECATED)",
4974 COMMAND_REGISTRATION_DONE
4977 struct FastLoad
4979 uint32_t address;
4980 uint8_t *data;
4981 int length;
4985 static int fastload_num;
4986 static struct FastLoad *fastload;
4988 static void free_fastload(void)
4990 if (fastload != NULL)
4992 int i;
4993 for (i = 0; i < fastload_num; i++)
4995 if (fastload[i].data)
4996 free(fastload[i].data);
4998 free(fastload);
4999 fastload = NULL;
5006 COMMAND_HANDLER(handle_fast_load_image_command)
5008 uint8_t *buffer;
5009 size_t buf_cnt;
5010 uint32_t image_size;
5011 uint32_t min_address = 0;
5012 uint32_t max_address = 0xffffffff;
5013 int i;
5015 struct image image;
5017 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5018 &image, &min_address, &max_address);
5019 if (ERROR_OK != retval)
5020 return retval;
5022 struct duration bench;
5023 duration_start(&bench);
5025 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5026 if (retval != ERROR_OK)
5028 return retval;
5031 image_size = 0x0;
5032 retval = ERROR_OK;
5033 fastload_num = image.num_sections;
5034 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5035 if (fastload == NULL)
5037 command_print(CMD_CTX, "out of memory");
5038 image_close(&image);
5039 return ERROR_FAIL;
5041 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5042 for (i = 0; i < image.num_sections; i++)
5044 buffer = malloc(image.sections[i].size);
5045 if (buffer == NULL)
5047 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5048 (int)(image.sections[i].size));
5049 retval = ERROR_FAIL;
5050 break;
5053 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
5055 free(buffer);
5056 break;
5059 uint32_t offset = 0;
5060 uint32_t length = buf_cnt;
5063 /* DANGER!!! beware of unsigned comparision here!!! */
5065 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
5066 (image.sections[i].base_address < max_address))
5068 if (image.sections[i].base_address < min_address)
5070 /* clip addresses below */
5071 offset += min_address-image.sections[i].base_address;
5072 length -= offset;
5075 if (image.sections[i].base_address + buf_cnt > max_address)
5077 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5080 fastload[i].address = image.sections[i].base_address + offset;
5081 fastload[i].data = malloc(length);
5082 if (fastload[i].data == NULL)
5084 free(buffer);
5085 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5086 length);
5087 retval = ERROR_FAIL;
5088 break;
5090 memcpy(fastload[i].data, buffer + offset, length);
5091 fastload[i].length = length;
5093 image_size += length;
5094 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5095 (unsigned int)length,
5096 ((unsigned int)(image.sections[i].base_address + offset)));
5099 free(buffer);
5102 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5104 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5105 "in %fs (%0.3f KiB/s)", image_size,
5106 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5108 command_print(CMD_CTX,
5109 "WARNING: image has not been loaded to target!"
5110 "You can issue a 'fast_load' to finish loading.");
5113 image_close(&image);
5115 if (retval != ERROR_OK)
5117 free_fastload();
5120 return retval;
5123 COMMAND_HANDLER(handle_fast_load_command)
5125 if (CMD_ARGC > 0)
5126 return ERROR_COMMAND_SYNTAX_ERROR;
5127 if (fastload == NULL)
5129 LOG_ERROR("No image in memory");
5130 return ERROR_FAIL;
5132 int i;
5133 int ms = timeval_ms();
5134 int size = 0;
5135 int retval = ERROR_OK;
5136 for (i = 0; i < fastload_num;i++)
5138 struct target *target = get_current_target(CMD_CTX);
5139 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5140 (unsigned int)(fastload[i].address),
5141 (unsigned int)(fastload[i].length));
5142 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5143 if (retval != ERROR_OK)
5145 break;
5147 size += fastload[i].length;
5149 if (retval == ERROR_OK)
5151 int after = timeval_ms();
5152 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5154 return retval;
5157 static const struct command_registration target_command_handlers[] = {
5159 .name = "targets",
5160 .handler = handle_targets_command,
5161 .mode = COMMAND_ANY,
5162 .help = "change current default target (one parameter) "
5163 "or prints table of all targets (no parameters)",
5164 .usage = "[target]",
5167 .name = "target",
5168 .mode = COMMAND_CONFIG,
5169 .help = "configure target",
5171 .chain = target_subcommand_handlers,
5173 COMMAND_REGISTRATION_DONE
5176 int target_register_commands(struct command_context *cmd_ctx)
5178 return register_commands(cmd_ctx, NULL, target_command_handlers);
5181 static bool target_reset_nag = true;
5183 bool get_target_reset_nag(void)
5185 return target_reset_nag;
5188 COMMAND_HANDLER(handle_target_reset_nag)
5190 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5191 &target_reset_nag, "Nag after each reset about options to improve "
5192 "performance");
5195 static const struct command_registration target_exec_command_handlers[] = {
5197 .name = "fast_load_image",
5198 .handler = handle_fast_load_image_command,
5199 .mode = COMMAND_ANY,
5200 .help = "Load image into server memory for later use by "
5201 "fast_load; primarily for profiling",
5202 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5203 "[min_address [max_length]]",
5206 .name = "fast_load",
5207 .handler = handle_fast_load_command,
5208 .mode = COMMAND_EXEC,
5209 .help = "loads active fast load image to current target "
5210 "- mainly for profiling purposes",
5213 .name = "profile",
5214 .handler = handle_profile_command,
5215 .mode = COMMAND_EXEC,
5216 .help = "profiling samples the CPU PC",
5218 /** @todo don't register virt2phys() unless target supports it */
5220 .name = "virt2phys",
5221 .handler = handle_virt2phys_command,
5222 .mode = COMMAND_ANY,
5223 .help = "translate a virtual address into a physical address",
5224 .usage = "virtual_address",
5227 .name = "reg",
5228 .handler = handle_reg_command,
5229 .mode = COMMAND_EXEC,
5230 .help = "display or set a register; with no arguments, "
5231 "displays all registers and their values",
5232 .usage = "[(register_name|register_number) [value]]",
5235 .name = "poll",
5236 .handler = handle_poll_command,
5237 .mode = COMMAND_EXEC,
5238 .help = "poll target state; or reconfigure background polling",
5239 .usage = "['on'|'off']",
5242 .name = "wait_halt",
5243 .handler = handle_wait_halt_command,
5244 .mode = COMMAND_EXEC,
5245 .help = "wait up to the specified number of milliseconds "
5246 "(default 5) for a previously requested halt",
5247 .usage = "[milliseconds]",
5250 .name = "halt",
5251 .handler = handle_halt_command,
5252 .mode = COMMAND_EXEC,
5253 .help = "request target to halt, then wait up to the specified"
5254 "number of milliseconds (default 5) for it to complete",
5255 .usage = "[milliseconds]",
5258 .name = "resume",
5259 .handler = handle_resume_command,
5260 .mode = COMMAND_EXEC,
5261 .help = "resume target execution from current PC or address",
5262 .usage = "[address]",
5265 .name = "reset",
5266 .handler = handle_reset_command,
5267 .mode = COMMAND_EXEC,
5268 .usage = "[run|halt|init]",
5269 .help = "Reset all targets into the specified mode."
5270 "Default reset mode is run, if not given.",
5273 .name = "soft_reset_halt",
5274 .handler = handle_soft_reset_halt_command,
5275 .mode = COMMAND_EXEC,
5276 .help = "halt the target and do a soft reset",
5279 .name = "step",
5280 .handler = handle_step_command,
5281 .mode = COMMAND_EXEC,
5282 .help = "step one instruction from current PC or address",
5283 .usage = "[address]",
5286 .name = "mdw",
5287 .handler = handle_md_command,
5288 .mode = COMMAND_EXEC,
5289 .help = "display memory words",
5290 .usage = "['phys'] address [count]",
5293 .name = "mdh",
5294 .handler = handle_md_command,
5295 .mode = COMMAND_EXEC,
5296 .help = "display memory half-words",
5297 .usage = "['phys'] address [count]",
5300 .name = "mdb",
5301 .handler = handle_md_command,
5302 .mode = COMMAND_EXEC,
5303 .help = "display memory bytes",
5304 .usage = "['phys'] address [count]",
5307 .name = "mww",
5308 .handler = handle_mw_command,
5309 .mode = COMMAND_EXEC,
5310 .help = "write memory word",
5311 .usage = "['phys'] address value [count]",
5314 .name = "mwh",
5315 .handler = handle_mw_command,
5316 .mode = COMMAND_EXEC,
5317 .help = "write memory half-word",
5318 .usage = "['phys'] address value [count]",
5321 .name = "mwb",
5322 .handler = handle_mw_command,
5323 .mode = COMMAND_EXEC,
5324 .help = "write memory byte",
5325 .usage = "['phys'] address value [count]",
5328 .name = "bp",
5329 .handler = handle_bp_command,
5330 .mode = COMMAND_EXEC,
5331 .help = "list or set hardware or software breakpoint",
5332 .usage = "[address length ['hw']]",
5335 .name = "rbp",
5336 .handler = handle_rbp_command,
5337 .mode = COMMAND_EXEC,
5338 .help = "remove breakpoint",
5339 .usage = "address",
5342 .name = "wp",
5343 .handler = handle_wp_command,
5344 .mode = COMMAND_EXEC,
5345 .help = "list (no params) or create watchpoints",
5346 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5349 .name = "rwp",
5350 .handler = handle_rwp_command,
5351 .mode = COMMAND_EXEC,
5352 .help = "remove watchpoint",
5353 .usage = "address",
5356 .name = "load_image",
5357 .handler = handle_load_image_command,
5358 .mode = COMMAND_EXEC,
5359 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5360 "[min_address] [max_length]",
5363 .name = "dump_image",
5364 .handler = handle_dump_image_command,
5365 .mode = COMMAND_EXEC,
5366 .usage = "filename address size",
5369 .name = "verify_image",
5370 .handler = handle_verify_image_command,
5371 .mode = COMMAND_EXEC,
5372 .usage = "filename [offset [type]]",
5375 .name = "test_image",
5376 .handler = handle_test_image_command,
5377 .mode = COMMAND_EXEC,
5378 .usage = "filename [offset [type]]",
5381 .name = "mem2array",
5382 .mode = COMMAND_EXEC,
5383 .jim_handler = jim_mem2array,
5384 .help = "read 8/16/32 bit memory and return as a TCL array "
5385 "for script processing",
5386 .usage = "arrayname bitwidth address count",
5389 .name = "array2mem",
5390 .mode = COMMAND_EXEC,
5391 .jim_handler = jim_array2mem,
5392 .help = "convert a TCL array to memory locations "
5393 "and write the 8/16/32 bit values",
5394 .usage = "arrayname bitwidth address count",
5397 .name = "reset_nag",
5398 .handler = handle_target_reset_nag,
5399 .mode = COMMAND_ANY,
5400 .help = "Nag after each reset about options that could have been "
5401 "enabled to improve performance. ",
5402 .usage = "['enable'|'disable']",
5404 COMMAND_REGISTRATION_DONE
5406 static int target_register_user_commands(struct command_context *cmd_ctx)
5408 int retval = ERROR_OK;
5409 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5410 return retval;
5412 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5413 return retval;
5416 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);