RTOS Thread awareness support wip
[openocd.git] / src / target / target.c
blobabe1b43ae03e01f5d79a464f5281d2cf93b23545
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 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
19 * *
20 * This program is free software; you can redistribute it and/or modify *
21 * it under the terms of the GNU General Public License as published by *
22 * the Free Software Foundation; either version 2 of the License, or *
23 * (at your option) any later version. *
24 * *
25 * This program is distributed in the hope that it will be useful, *
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
28 * GNU General Public License for more details. *
29 * *
30 * You should have received a copy of the GNU General Public License *
31 * along with this program; if not, write to the *
32 * Free Software Foundation, Inc., *
33 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
34 ***************************************************************************/
35 #ifdef HAVE_CONFIG_H
36 #include "config.h"
37 #endif
39 #include <helper/time_support.h>
40 #include <jtag/jtag.h>
41 #include <flash/nor/core.h>
43 #include "target.h"
44 #include "target_type.h"
45 #include "target_request.h"
46 #include "breakpoints.h"
47 #include "register.h"
48 #include "trace.h"
49 #include "image.h"
50 #include "rtos/rtos.h"
53 static int target_read_buffer_default(struct target *target, uint32_t address,
54 uint32_t size, uint8_t *buffer);
55 static int target_write_buffer_default(struct target *target, uint32_t address,
56 uint32_t size, const uint8_t *buffer);
57 static int target_array2mem(Jim_Interp *interp, struct target *target,
58 int argc, Jim_Obj *const *argv);
59 static int target_mem2array(Jim_Interp *interp, struct target *target,
60 int argc, Jim_Obj *const *argv);
61 static int target_register_user_commands(struct command_context *cmd_ctx);
63 /* targets */
64 extern struct target_type arm7tdmi_target;
65 extern struct target_type arm720t_target;
66 extern struct target_type arm9tdmi_target;
67 extern struct target_type arm920t_target;
68 extern struct target_type arm966e_target;
69 extern struct target_type arm946e_target;
70 extern struct target_type arm926ejs_target;
71 extern struct target_type fa526_target;
72 extern struct target_type feroceon_target;
73 extern struct target_type dragonite_target;
74 extern struct target_type xscale_target;
75 extern struct target_type cortexm3_target;
76 extern struct target_type cortexa8_target;
77 extern struct target_type arm11_target;
78 extern struct target_type mips_m4k_target;
79 extern struct target_type avr_target;
80 extern struct target_type dsp563xx_target;
81 extern struct target_type testee_target;
82 extern struct target_type avr32_ap7k_target;
84 static struct target_type *target_types[] =
86 &arm7tdmi_target,
87 &arm9tdmi_target,
88 &arm920t_target,
89 &arm720t_target,
90 &arm966e_target,
91 &arm946e_target,
92 &arm926ejs_target,
93 &fa526_target,
94 &feroceon_target,
95 &dragonite_target,
96 &xscale_target,
97 &cortexm3_target,
98 &cortexa8_target,
99 &arm11_target,
100 &mips_m4k_target,
101 &avr_target,
102 &dsp563xx_target,
103 &testee_target,
104 &avr32_ap7k_target,
105 NULL,
108 struct target *all_targets = NULL;
109 static struct target_event_callback *target_event_callbacks = NULL;
110 static struct target_timer_callback *target_timer_callbacks = NULL;
111 static const int polling_interval = 100;
113 static const Jim_Nvp nvp_assert[] = {
114 { .name = "assert", NVP_ASSERT },
115 { .name = "deassert", NVP_DEASSERT },
116 { .name = "T", NVP_ASSERT },
117 { .name = "F", NVP_DEASSERT },
118 { .name = "t", NVP_ASSERT },
119 { .name = "f", NVP_DEASSERT },
120 { .name = NULL, .value = -1 }
123 static const Jim_Nvp nvp_error_target[] = {
124 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
125 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
126 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
127 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
128 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
129 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
130 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
131 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
132 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
133 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
134 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
135 { .value = -1, .name = NULL }
138 static const char *target_strerror_safe(int err)
140 const Jim_Nvp *n;
142 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
143 if (n->name == NULL) {
144 return "unknown";
145 } else {
146 return n->name;
150 static const Jim_Nvp nvp_target_event[] = {
151 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
152 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
154 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
155 { .value = TARGET_EVENT_HALTED, .name = "halted" },
156 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
157 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
158 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
160 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
161 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
163 /* historical name */
165 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
167 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
168 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
169 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
170 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
171 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
172 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
173 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
174 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
175 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
176 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
177 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
179 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
180 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
182 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
183 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
185 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
186 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
188 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
189 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
191 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
192 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
194 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
195 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
196 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
198 { .name = NULL, .value = -1 }
201 static const Jim_Nvp nvp_target_state[] = {
202 { .name = "unknown", .value = TARGET_UNKNOWN },
203 { .name = "running", .value = TARGET_RUNNING },
204 { .name = "halted", .value = TARGET_HALTED },
205 { .name = "reset", .value = TARGET_RESET },
206 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
207 { .name = NULL, .value = -1 },
210 static const Jim_Nvp nvp_target_debug_reason [] = {
211 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
212 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
213 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
214 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
215 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
216 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
217 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
218 { .name = NULL, .value = -1 },
221 static const Jim_Nvp nvp_target_endian[] = {
222 { .name = "big", .value = TARGET_BIG_ENDIAN },
223 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
224 { .name = "be", .value = TARGET_BIG_ENDIAN },
225 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
226 { .name = NULL, .value = -1 },
229 static const Jim_Nvp nvp_reset_modes[] = {
230 { .name = "unknown", .value = RESET_UNKNOWN },
231 { .name = "run" , .value = RESET_RUN },
232 { .name = "halt" , .value = RESET_HALT },
233 { .name = "init" , .value = RESET_INIT },
234 { .name = NULL , .value = -1 },
237 const char *debug_reason_name(struct target *t)
239 const char *cp;
241 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
242 t->debug_reason)->name;
243 if (!cp) {
244 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
245 cp = "(*BUG*unknown*BUG*)";
247 return cp;
250 const char *
251 target_state_name( struct target *t )
253 const char *cp;
254 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
255 if( !cp ){
256 LOG_ERROR("Invalid target state: %d", (int)(t->state));
257 cp = "(*BUG*unknown*BUG*)";
259 return cp;
262 /* determine the number of the new target */
263 static int new_target_number(void)
265 struct target *t;
266 int x;
268 /* number is 0 based */
269 x = -1;
270 t = all_targets;
271 while (t) {
272 if (x < t->target_number) {
273 x = t->target_number;
275 t = t->next;
277 return x + 1;
280 /* read a uint32_t from a buffer in target memory endianness */
281 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
283 if (target->endianness == TARGET_LITTLE_ENDIAN)
284 return le_to_h_u32(buffer);
285 else
286 return be_to_h_u32(buffer);
289 /* read a uint24_t from a buffer in target memory endianness */
290 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
292 if (target->endianness == TARGET_LITTLE_ENDIAN)
293 return le_to_h_u24(buffer);
294 else
295 return be_to_h_u24(buffer);
298 /* read a uint16_t from a buffer in target memory endianness */
299 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
301 if (target->endianness == TARGET_LITTLE_ENDIAN)
302 return le_to_h_u16(buffer);
303 else
304 return be_to_h_u16(buffer);
307 /* read a uint8_t from a buffer in target memory endianness */
308 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
310 return *buffer & 0x0ff;
313 /* write a uint32_t to a buffer in target memory endianness */
314 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
316 if (target->endianness == TARGET_LITTLE_ENDIAN)
317 h_u32_to_le(buffer, value);
318 else
319 h_u32_to_be(buffer, value);
322 /* write a uint24_t to a buffer in target memory endianness */
323 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
325 if (target->endianness == TARGET_LITTLE_ENDIAN)
326 h_u24_to_le(buffer, value);
327 else
328 h_u24_to_be(buffer, value);
331 /* write a uint16_t to a buffer in target memory endianness */
332 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
334 if (target->endianness == TARGET_LITTLE_ENDIAN)
335 h_u16_to_le(buffer, value);
336 else
337 h_u16_to_be(buffer, value);
340 /* write a uint8_t to a buffer in target memory endianness */
341 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
343 *buffer = value;
346 /* return a pointer to a configured target; id is name or number */
347 struct target *get_target(const char *id)
349 struct target *target;
351 /* try as tcltarget name */
352 for (target = all_targets; target; target = target->next) {
353 if (target->cmd_name == NULL)
354 continue;
355 if (strcmp(id, target->cmd_name) == 0)
356 return target;
359 /* It's OK to remove this fallback sometime after August 2010 or so */
361 /* no match, try as number */
362 unsigned num;
363 if (parse_uint(id, &num) != ERROR_OK)
364 return NULL;
366 for (target = all_targets; target; target = target->next) {
367 if (target->target_number == (int)num) {
368 LOG_WARNING("use '%s' as target identifier, not '%u'",
369 target->cmd_name, num);
370 return target;
374 return NULL;
377 /* returns a pointer to the n-th configured target */
378 static struct target *get_target_by_num(int num)
380 struct target *target = all_targets;
382 while (target) {
383 if (target->target_number == num) {
384 return target;
386 target = target->next;
389 return NULL;
392 struct target* get_current_target(struct command_context *cmd_ctx)
394 struct target *target = get_target_by_num(cmd_ctx->current_target);
396 if (target == NULL)
398 LOG_ERROR("BUG: current_target out of bounds");
399 exit(-1);
402 return target;
405 int target_poll(struct target *target)
407 int retval;
409 /* We can't poll until after examine */
410 if (!target_was_examined(target))
412 /* Fail silently lest we pollute the log */
413 return ERROR_FAIL;
416 retval = target->type->poll(target);
417 if (retval != ERROR_OK)
418 return retval;
420 if (target->halt_issued)
422 if (target->state == TARGET_HALTED)
424 target->halt_issued = false;
425 } else
427 long long t = timeval_ms() - target->halt_issued_time;
428 if (t>1000)
430 target->halt_issued = false;
431 LOG_INFO("Halt timed out, wake up GDB.");
432 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
437 return ERROR_OK;
440 int target_halt(struct target *target)
442 int retval;
443 /* We can't poll until after examine */
444 if (!target_was_examined(target))
446 LOG_ERROR("Target not examined yet");
447 return ERROR_FAIL;
450 retval = target->type->halt(target);
451 if (retval != ERROR_OK)
452 return retval;
454 target->halt_issued = true;
455 target->halt_issued_time = timeval_ms();
457 return ERROR_OK;
461 * Make the target (re)start executing using its saved execution
462 * context (possibly with some modifications).
464 * @param target Which target should start executing.
465 * @param current True to use the target's saved program counter instead
466 * of the address parameter
467 * @param address Optionally used as the program counter.
468 * @param handle_breakpoints True iff breakpoints at the resumption PC
469 * should be skipped. (For example, maybe execution was stopped by
470 * such a breakpoint, in which case it would be counterprodutive to
471 * let it re-trigger.
472 * @param debug_execution False if all working areas allocated by OpenOCD
473 * should be released and/or restored to their original contents.
474 * (This would for example be true to run some downloaded "helper"
475 * algorithm code, which resides in one such working buffer and uses
476 * another for data storage.)
478 * @todo Resolve the ambiguity about what the "debug_execution" flag
479 * signifies. For example, Target implementations don't agree on how
480 * it relates to invalidation of the register cache, or to whether
481 * breakpoints and watchpoints should be enabled. (It would seem wrong
482 * to enable breakpoints when running downloaded "helper" algorithms
483 * (debug_execution true), since the breakpoints would be set to match
484 * target firmware being debugged, not the helper algorithm.... and
485 * enabling them could cause such helpers to malfunction (for example,
486 * by overwriting data with a breakpoint instruction. On the other
487 * hand the infrastructure for running such helpers might use this
488 * procedure but rely on hardware breakpoint to detect termination.)
490 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
492 int retval;
494 /* We can't poll until after examine */
495 if (!target_was_examined(target))
497 LOG_ERROR("Target not examined yet");
498 return ERROR_FAIL;
501 /* note that resume *must* be asynchronous. The CPU can halt before
502 * we poll. The CPU can even halt at the current PC as a result of
503 * a software breakpoint being inserted by (a bug?) the application.
505 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
506 return retval;
508 return retval;
511 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
513 char buf[100];
514 int retval;
515 Jim_Nvp *n;
516 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
517 if (n->name == NULL) {
518 LOG_ERROR("invalid reset mode");
519 return ERROR_FAIL;
522 /* disable polling during reset to make reset event scripts
523 * more predictable, i.e. dr/irscan & pathmove in events will
524 * not have JTAG operations injected into the middle of a sequence.
526 bool save_poll = jtag_poll_get_enabled();
528 jtag_poll_set_enabled(false);
530 sprintf(buf, "ocd_process_reset %s", n->name);
531 retval = Jim_Eval(cmd_ctx->interp, buf);
533 jtag_poll_set_enabled(save_poll);
535 if (retval != JIM_OK) {
536 Jim_MakeErrorMessage(cmd_ctx->interp);
537 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
538 return ERROR_FAIL;
541 /* We want any events to be processed before the prompt */
542 retval = target_call_timer_callbacks_now();
544 struct target *target;
545 for (target = all_targets; target; target = target->next) {
546 target->type->check_reset(target);
549 return retval;
552 static int identity_virt2phys(struct target *target,
553 uint32_t virtual, uint32_t *physical)
555 *physical = virtual;
556 return ERROR_OK;
559 static int no_mmu(struct target *target, int *enabled)
561 *enabled = 0;
562 return ERROR_OK;
565 static int default_examine(struct target *target)
567 target_set_examined(target);
568 return ERROR_OK;
571 /* no check by default */
572 static int default_check_reset(struct target *target)
574 return ERROR_OK;
577 int target_examine_one(struct target *target)
579 return target->type->examine(target);
582 static int jtag_enable_callback(enum jtag_event event, void *priv)
584 struct target *target = priv;
586 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
587 return ERROR_OK;
589 jtag_unregister_event_callback(jtag_enable_callback, target);
590 return target_examine_one(target);
594 /* Targets that correctly implement init + examine, i.e.
595 * no communication with target during init:
597 * XScale
599 int target_examine(void)
601 int retval = ERROR_OK;
602 struct target *target;
604 for (target = all_targets; target; target = target->next)
606 /* defer examination, but don't skip it */
607 if (!target->tap->enabled) {
608 jtag_register_event_callback(jtag_enable_callback,
609 target);
610 continue;
612 if ((retval = target_examine_one(target)) != ERROR_OK)
613 return retval;
615 return retval;
617 const char *target_type_name(struct target *target)
619 return target->type->name;
622 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
624 if (!target_was_examined(target))
626 LOG_ERROR("Target not examined yet");
627 return ERROR_FAIL;
629 return target->type->write_memory_imp(target, address, size, count, buffer);
632 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
634 if (!target_was_examined(target))
636 LOG_ERROR("Target not examined yet");
637 return ERROR_FAIL;
639 return target->type->read_memory_imp(target, address, size, count, buffer);
642 static int target_soft_reset_halt_imp(struct target *target)
644 if (!target_was_examined(target))
646 LOG_ERROR("Target not examined yet");
647 return ERROR_FAIL;
649 if (!target->type->soft_reset_halt_imp) {
650 LOG_ERROR("Target %s does not support soft_reset_halt",
651 target_name(target));
652 return ERROR_FAIL;
654 return target->type->soft_reset_halt_imp(target);
658 * Downloads a target-specific native code algorithm to the target,
659 * and executes it. * Note that some targets may need to set up, enable,
660 * and tear down a breakpoint (hard or * soft) to detect algorithm
661 * termination, while others may support lower overhead schemes where
662 * soft breakpoints embedded in the algorithm automatically terminate the
663 * algorithm.
665 * @param target used to run the algorithm
666 * @param arch_info target-specific description of the algorithm.
668 int target_run_algorithm(struct target *target,
669 int num_mem_params, struct mem_param *mem_params,
670 int num_reg_params, struct reg_param *reg_param,
671 uint32_t entry_point, uint32_t exit_point,
672 int timeout_ms, void *arch_info)
674 int retval = ERROR_FAIL;
676 if (!target_was_examined(target))
678 LOG_ERROR("Target not examined yet");
679 goto done;
681 if (!target->type->run_algorithm) {
682 LOG_ERROR("Target type '%s' does not support %s",
683 target_type_name(target), __func__);
684 goto done;
687 target->running_alg = true;
688 retval = target->type->run_algorithm(target,
689 num_mem_params, mem_params,
690 num_reg_params, reg_param,
691 entry_point, exit_point, timeout_ms, arch_info);
692 target->running_alg = false;
694 done:
695 return retval;
699 int target_read_memory(struct target *target,
700 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
702 return target->type->read_memory(target, address, size, count, buffer);
705 static int target_read_phys_memory(struct target *target,
706 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
708 return target->type->read_phys_memory(target, address, size, count, buffer);
711 int target_write_memory(struct target *target,
712 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
714 return target->type->write_memory(target, address, size, count, buffer);
717 static int target_write_phys_memory(struct target *target,
718 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
720 return target->type->write_phys_memory(target, address, size, count, buffer);
723 int target_bulk_write_memory(struct target *target,
724 uint32_t address, uint32_t count, const uint8_t *buffer)
726 return target->type->bulk_write_memory(target, address, count, buffer);
729 int target_add_breakpoint(struct target *target,
730 struct breakpoint *breakpoint)
732 if (target->state != TARGET_HALTED) {
733 LOG_WARNING("target %s is not halted", target->cmd_name);
734 return ERROR_TARGET_NOT_HALTED;
736 return target->type->add_breakpoint(target, breakpoint);
738 int target_remove_breakpoint(struct target *target,
739 struct breakpoint *breakpoint)
741 return target->type->remove_breakpoint(target, breakpoint);
744 int target_add_watchpoint(struct target *target,
745 struct watchpoint *watchpoint)
747 if (target->state != TARGET_HALTED) {
748 LOG_WARNING("target %s is not halted", target->cmd_name);
749 return ERROR_TARGET_NOT_HALTED;
751 return target->type->add_watchpoint(target, watchpoint);
753 int target_remove_watchpoint(struct target *target,
754 struct watchpoint *watchpoint)
756 return target->type->remove_watchpoint(target, watchpoint);
759 int target_get_gdb_reg_list(struct target *target,
760 struct reg **reg_list[], int *reg_list_size)
762 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
764 int target_step(struct target *target,
765 int current, uint32_t address, int handle_breakpoints)
767 return target->type->step(target, current, address, handle_breakpoints);
772 * Reset the @c examined flag for the given target.
773 * Pure paranoia -- targets are zeroed on allocation.
775 static void target_reset_examined(struct target *target)
777 target->examined = false;
780 static int
781 err_read_phys_memory(struct target *target, uint32_t address,
782 uint32_t size, uint32_t count, uint8_t *buffer)
784 LOG_ERROR("Not implemented: %s", __func__);
785 return ERROR_FAIL;
788 static int
789 err_write_phys_memory(struct target *target, uint32_t address,
790 uint32_t size, uint32_t count, const uint8_t *buffer)
792 LOG_ERROR("Not implemented: %s", __func__);
793 return ERROR_FAIL;
796 static int handle_target(void *priv);
798 static int target_init_one(struct command_context *cmd_ctx,
799 struct target *target)
801 target_reset_examined(target);
803 struct target_type *type = target->type;
804 if (type->examine == NULL)
805 type->examine = default_examine;
807 if (type->check_reset== NULL)
808 type->check_reset = default_check_reset;
810 int retval = type->init_target(cmd_ctx, target);
811 if (ERROR_OK != retval)
813 LOG_ERROR("target '%s' init failed", target_name(target));
814 return retval;
818 * @todo get rid of those *memory_imp() methods, now that all
819 * callers are using target_*_memory() accessors ... and make
820 * sure the "physical" paths handle the same issues.
822 /* a non-invasive way(in terms of patches) to add some code that
823 * runs before the type->write/read_memory implementation
825 type->write_memory_imp = target->type->write_memory;
826 type->write_memory = target_write_memory_imp;
828 type->read_memory_imp = target->type->read_memory;
829 type->read_memory = target_read_memory_imp;
831 type->soft_reset_halt_imp = target->type->soft_reset_halt;
832 type->soft_reset_halt = target_soft_reset_halt_imp;
834 /* Sanity-check MMU support ... stub in what we must, to help
835 * implement it in stages, but warn if we need to do so.
837 if (type->mmu)
839 if (type->write_phys_memory == NULL)
841 LOG_ERROR("type '%s' is missing write_phys_memory",
842 type->name);
843 type->write_phys_memory = err_write_phys_memory;
845 if (type->read_phys_memory == NULL)
847 LOG_ERROR("type '%s' is missing read_phys_memory",
848 type->name);
849 type->read_phys_memory = err_read_phys_memory;
851 if (type->virt2phys == NULL)
853 LOG_ERROR("type '%s' is missing virt2phys", type->name);
854 type->virt2phys = identity_virt2phys;
857 else
859 /* Make sure no-MMU targets all behave the same: make no
860 * distinction between physical and virtual addresses, and
861 * ensure that virt2phys() is always an identity mapping.
863 if (type->write_phys_memory || type->read_phys_memory
864 || type->virt2phys)
866 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
869 type->mmu = no_mmu;
870 type->write_phys_memory = type->write_memory;
871 type->read_phys_memory = type->read_memory;
872 type->virt2phys = identity_virt2phys;
875 if (target->type->read_buffer == NULL)
876 target->type->read_buffer = target_read_buffer_default;
878 if (target->type->write_buffer == NULL)
879 target->type->write_buffer = target_write_buffer_default;
881 return ERROR_OK;
884 static int target_init(struct command_context *cmd_ctx)
886 struct target *target;
887 int retval;
889 for (target = all_targets; target; target = target->next)
891 retval = target_init_one(cmd_ctx, target);
892 if (ERROR_OK != retval)
893 return retval;
896 if (!all_targets)
897 return ERROR_OK;
899 retval = target_register_user_commands(cmd_ctx);
900 if (ERROR_OK != retval)
901 return retval;
903 retval = target_register_timer_callback(&handle_target,
904 polling_interval, 1, cmd_ctx->interp);
905 if (ERROR_OK != retval)
906 return retval;
908 return ERROR_OK;
911 COMMAND_HANDLER(handle_target_init_command)
913 if (CMD_ARGC != 0)
914 return ERROR_COMMAND_SYNTAX_ERROR;
916 static bool target_initialized = false;
917 if (target_initialized)
919 LOG_INFO("'target init' has already been called");
920 return ERROR_OK;
922 target_initialized = true;
924 LOG_DEBUG("Initializing targets...");
925 return target_init(CMD_CTX);
928 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
930 struct target_event_callback **callbacks_p = &target_event_callbacks;
932 if (callback == NULL)
934 return ERROR_INVALID_ARGUMENTS;
937 if (*callbacks_p)
939 while ((*callbacks_p)->next)
940 callbacks_p = &((*callbacks_p)->next);
941 callbacks_p = &((*callbacks_p)->next);
944 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
945 (*callbacks_p)->callback = callback;
946 (*callbacks_p)->priv = priv;
947 (*callbacks_p)->next = NULL;
949 return ERROR_OK;
952 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
954 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
955 struct timeval now;
957 if (callback == NULL)
959 return ERROR_INVALID_ARGUMENTS;
962 if (*callbacks_p)
964 while ((*callbacks_p)->next)
965 callbacks_p = &((*callbacks_p)->next);
966 callbacks_p = &((*callbacks_p)->next);
969 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
970 (*callbacks_p)->callback = callback;
971 (*callbacks_p)->periodic = periodic;
972 (*callbacks_p)->time_ms = time_ms;
974 gettimeofday(&now, NULL);
975 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
976 time_ms -= (time_ms % 1000);
977 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
978 if ((*callbacks_p)->when.tv_usec > 1000000)
980 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
981 (*callbacks_p)->when.tv_sec += 1;
984 (*callbacks_p)->priv = priv;
985 (*callbacks_p)->next = NULL;
987 return ERROR_OK;
990 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
992 struct target_event_callback **p = &target_event_callbacks;
993 struct target_event_callback *c = target_event_callbacks;
995 if (callback == NULL)
997 return ERROR_INVALID_ARGUMENTS;
1000 while (c)
1002 struct target_event_callback *next = c->next;
1003 if ((c->callback == callback) && (c->priv == priv))
1005 *p = next;
1006 free(c);
1007 return ERROR_OK;
1009 else
1010 p = &(c->next);
1011 c = next;
1014 return ERROR_OK;
1017 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1019 struct target_timer_callback **p = &target_timer_callbacks;
1020 struct target_timer_callback *c = target_timer_callbacks;
1022 if (callback == NULL)
1024 return ERROR_INVALID_ARGUMENTS;
1027 while (c)
1029 struct target_timer_callback *next = c->next;
1030 if ((c->callback == callback) && (c->priv == priv))
1032 *p = next;
1033 free(c);
1034 return ERROR_OK;
1036 else
1037 p = &(c->next);
1038 c = next;
1041 return ERROR_OK;
1044 int target_call_event_callbacks(struct target *target, enum target_event event)
1046 struct target_event_callback *callback = target_event_callbacks;
1047 struct target_event_callback *next_callback;
1049 if (event == TARGET_EVENT_HALTED)
1051 /* execute early halted first */
1052 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1055 LOG_DEBUG("target event %i (%s)",
1056 event,
1057 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1059 target_handle_event(target, event);
1061 while (callback)
1063 next_callback = callback->next;
1064 callback->callback(target, event, callback->priv);
1065 callback = next_callback;
1068 return ERROR_OK;
1071 static int target_timer_callback_periodic_restart(
1072 struct target_timer_callback *cb, struct timeval *now)
1074 int time_ms = cb->time_ms;
1075 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1076 time_ms -= (time_ms % 1000);
1077 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1078 if (cb->when.tv_usec > 1000000)
1080 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1081 cb->when.tv_sec += 1;
1083 return ERROR_OK;
1086 static int target_call_timer_callback(struct target_timer_callback *cb,
1087 struct timeval *now)
1089 cb->callback(cb->priv);
1091 if (cb->periodic)
1092 return target_timer_callback_periodic_restart(cb, now);
1094 return target_unregister_timer_callback(cb->callback, cb->priv);
1097 static int target_call_timer_callbacks_check_time(int checktime)
1099 keep_alive();
1101 struct timeval now;
1102 gettimeofday(&now, NULL);
1104 struct target_timer_callback *callback = target_timer_callbacks;
1105 while (callback)
1107 // cleaning up may unregister and free this callback
1108 struct target_timer_callback *next_callback = callback->next;
1110 bool call_it = callback->callback &&
1111 ((!checktime && callback->periodic) ||
1112 now.tv_sec > callback->when.tv_sec ||
1113 (now.tv_sec == callback->when.tv_sec &&
1114 now.tv_usec >= callback->when.tv_usec));
1116 if (call_it)
1118 int retval = target_call_timer_callback(callback, &now);
1119 if (retval != ERROR_OK)
1120 return retval;
1123 callback = next_callback;
1126 return ERROR_OK;
1129 int target_call_timer_callbacks(void)
1131 return target_call_timer_callbacks_check_time(1);
1134 /* invoke periodic callbacks immediately */
1135 int target_call_timer_callbacks_now(void)
1137 return target_call_timer_callbacks_check_time(0);
1140 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1142 struct working_area *c = target->working_areas;
1143 struct working_area *new_wa = NULL;
1145 /* Reevaluate working area address based on MMU state*/
1146 if (target->working_areas == NULL)
1148 int retval;
1149 int enabled;
1151 retval = target->type->mmu(target, &enabled);
1152 if (retval != ERROR_OK)
1154 return retval;
1157 if (!enabled) {
1158 if (target->working_area_phys_spec) {
1159 LOG_DEBUG("MMU disabled, using physical "
1160 "address for working memory 0x%08x",
1161 (unsigned)target->working_area_phys);
1162 target->working_area = target->working_area_phys;
1163 } else {
1164 LOG_ERROR("No working memory available. "
1165 "Specify -work-area-phys to target.");
1166 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1168 } else {
1169 if (target->working_area_virt_spec) {
1170 LOG_DEBUG("MMU enabled, using virtual "
1171 "address for working memory 0x%08x",
1172 (unsigned)target->working_area_virt);
1173 target->working_area = target->working_area_virt;
1174 } else {
1175 LOG_ERROR("No working memory available. "
1176 "Specify -work-area-virt to target.");
1177 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1182 /* only allocate multiples of 4 byte */
1183 if (size % 4)
1185 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1186 size = (size + 3) & (~3);
1189 /* see if there's already a matching working area */
1190 while (c)
1192 if ((c->free) && (c->size == size))
1194 new_wa = c;
1195 break;
1197 c = c->next;
1200 /* if not, allocate a new one */
1201 if (!new_wa)
1203 struct working_area **p = &target->working_areas;
1204 uint32_t first_free = target->working_area;
1205 uint32_t free_size = target->working_area_size;
1207 c = target->working_areas;
1208 while (c)
1210 first_free += c->size;
1211 free_size -= c->size;
1212 p = &c->next;
1213 c = c->next;
1216 if (free_size < size)
1218 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1221 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1223 new_wa = malloc(sizeof(struct working_area));
1224 new_wa->next = NULL;
1225 new_wa->size = size;
1226 new_wa->address = first_free;
1228 if (target->backup_working_area)
1230 int retval;
1231 new_wa->backup = malloc(new_wa->size);
1232 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1234 free(new_wa->backup);
1235 free(new_wa);
1236 return retval;
1239 else
1241 new_wa->backup = NULL;
1244 /* put new entry in list */
1245 *p = new_wa;
1248 /* mark as used, and return the new (reused) area */
1249 new_wa->free = false;
1250 *area = new_wa;
1252 /* user pointer */
1253 new_wa->user = area;
1255 return ERROR_OK;
1258 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1260 int retval;
1262 retval = target_alloc_working_area_try(target, size, area);
1263 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1265 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1267 return retval;
1271 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1273 if (area->free)
1274 return ERROR_OK;
1276 if (restore && target->backup_working_area)
1278 int retval;
1279 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1280 return retval;
1283 area->free = true;
1285 /* mark user pointer invalid */
1286 *area->user = NULL;
1287 area->user = NULL;
1289 return ERROR_OK;
1292 int target_free_working_area(struct target *target, struct working_area *area)
1294 return target_free_working_area_restore(target, area, 1);
1297 /* free resources and restore memory, if restoring memory fails,
1298 * free up resources anyway
1300 static void target_free_all_working_areas_restore(struct target *target, int restore)
1302 struct working_area *c = target->working_areas;
1304 while (c)
1306 struct working_area *next = c->next;
1307 target_free_working_area_restore(target, c, restore);
1309 if (c->backup)
1310 free(c->backup);
1312 free(c);
1314 c = next;
1317 target->working_areas = NULL;
1320 void target_free_all_working_areas(struct target *target)
1322 target_free_all_working_areas_restore(target, 1);
1325 int target_arch_state(struct target *target)
1327 int retval;
1328 if (target == NULL)
1330 LOG_USER("No target has been configured");
1331 return ERROR_OK;
1334 LOG_USER("target state: %s", target_state_name( target ));
1336 if (target->state != TARGET_HALTED)
1337 return ERROR_OK;
1339 retval = target->type->arch_state(target);
1340 return retval;
1343 /* Single aligned words are guaranteed to use 16 or 32 bit access
1344 * mode respectively, otherwise data is handled as quickly as
1345 * possible
1347 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1349 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1350 (int)size, (unsigned)address);
1352 if (!target_was_examined(target))
1354 LOG_ERROR("Target not examined yet");
1355 return ERROR_FAIL;
1358 if (size == 0) {
1359 return ERROR_OK;
1362 if ((address + size - 1) < address)
1364 /* GDB can request this when e.g. PC is 0xfffffffc*/
1365 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1366 (unsigned)address,
1367 (unsigned)size);
1368 return ERROR_FAIL;
1371 return target->type->write_buffer(target, address, size, buffer);
1374 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1376 int retval = ERROR_OK;
1378 if (((address % 2) == 0) && (size == 2))
1380 return target_write_memory(target, address, 2, 1, buffer);
1383 /* handle unaligned head bytes */
1384 if (address % 4)
1386 uint32_t unaligned = 4 - (address % 4);
1388 if (unaligned > size)
1389 unaligned = size;
1391 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1392 return retval;
1394 buffer += unaligned;
1395 address += unaligned;
1396 size -= unaligned;
1399 /* handle aligned words */
1400 if (size >= 4)
1402 int aligned = size - (size % 4);
1404 /* use bulk writes above a certain limit. This may have to be changed */
1405 if (aligned > 128)
1407 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1408 return retval;
1410 else
1412 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1413 return retval;
1416 buffer += aligned;
1417 address += aligned;
1418 size -= aligned;
1421 /* handle tail writes of less than 4 bytes */
1422 if (size > 0)
1424 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1425 return retval;
1428 return retval;
1431 /* Single aligned words are guaranteed to use 16 or 32 bit access
1432 * mode respectively, otherwise data is handled as quickly as
1433 * possible
1435 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1437 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1438 (int)size, (unsigned)address);
1440 if (!target_was_examined(target))
1442 LOG_ERROR("Target not examined yet");
1443 return ERROR_FAIL;
1446 if (size == 0) {
1447 return ERROR_OK;
1450 if ((address + size - 1) < address)
1452 /* GDB can request this when e.g. PC is 0xfffffffc*/
1453 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1454 address,
1455 size);
1456 return ERROR_FAIL;
1459 return target->type->read_buffer(target, address, size, buffer);
1462 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1464 int retval = ERROR_OK;
1466 if (((address % 2) == 0) && (size == 2))
1468 return target_read_memory(target, address, 2, 1, buffer);
1471 /* handle unaligned head bytes */
1472 if (address % 4)
1474 uint32_t unaligned = 4 - (address % 4);
1476 if (unaligned > size)
1477 unaligned = size;
1479 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1480 return retval;
1482 buffer += unaligned;
1483 address += unaligned;
1484 size -= unaligned;
1487 /* handle aligned words */
1488 if (size >= 4)
1490 int aligned = size - (size % 4);
1492 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1493 return retval;
1495 buffer += aligned;
1496 address += aligned;
1497 size -= aligned;
1500 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1501 if(size >=2)
1503 int aligned = size - (size%2);
1504 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1505 if (retval != ERROR_OK)
1506 return retval;
1508 buffer += aligned;
1509 address += aligned;
1510 size -= aligned;
1512 /* handle tail writes of less than 4 bytes */
1513 if (size > 0)
1515 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1516 return retval;
1519 return ERROR_OK;
1522 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1524 uint8_t *buffer;
1525 int retval;
1526 uint32_t i;
1527 uint32_t checksum = 0;
1528 if (!target_was_examined(target))
1530 LOG_ERROR("Target not examined yet");
1531 return ERROR_FAIL;
1534 if ((retval = target->type->checksum_memory(target, address,
1535 size, &checksum)) != ERROR_OK)
1537 buffer = malloc(size);
1538 if (buffer == NULL)
1540 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1541 return ERROR_INVALID_ARGUMENTS;
1543 retval = target_read_buffer(target, address, size, buffer);
1544 if (retval != ERROR_OK)
1546 free(buffer);
1547 return retval;
1550 /* convert to target endianness */
1551 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1553 uint32_t target_data;
1554 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1555 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1558 retval = image_calculate_checksum(buffer, size, &checksum);
1559 free(buffer);
1562 *crc = checksum;
1564 return retval;
1567 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1569 int retval;
1570 if (!target_was_examined(target))
1572 LOG_ERROR("Target not examined yet");
1573 return ERROR_FAIL;
1576 if (target->type->blank_check_memory == 0)
1577 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1579 retval = target->type->blank_check_memory(target, address, size, blank);
1581 return retval;
1584 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1586 uint8_t value_buf[4];
1587 if (!target_was_examined(target))
1589 LOG_ERROR("Target not examined yet");
1590 return ERROR_FAIL;
1593 int retval = target_read_memory(target, address, 4, 1, value_buf);
1595 if (retval == ERROR_OK)
1597 *value = target_buffer_get_u32(target, value_buf);
1598 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1599 address,
1600 *value);
1602 else
1604 *value = 0x0;
1605 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1606 address);
1609 return retval;
1612 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1614 uint8_t value_buf[2];
1615 if (!target_was_examined(target))
1617 LOG_ERROR("Target not examined yet");
1618 return ERROR_FAIL;
1621 int retval = target_read_memory(target, address, 2, 1, value_buf);
1623 if (retval == ERROR_OK)
1625 *value = target_buffer_get_u16(target, value_buf);
1626 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1627 address,
1628 *value);
1630 else
1632 *value = 0x0;
1633 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1634 address);
1637 return retval;
1640 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1642 int retval = target_read_memory(target, address, 1, 1, value);
1643 if (!target_was_examined(target))
1645 LOG_ERROR("Target not examined yet");
1646 return ERROR_FAIL;
1649 if (retval == ERROR_OK)
1651 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1652 address,
1653 *value);
1655 else
1657 *value = 0x0;
1658 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1659 address);
1662 return retval;
1665 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1667 int retval;
1668 uint8_t value_buf[4];
1669 if (!target_was_examined(target))
1671 LOG_ERROR("Target not examined yet");
1672 return ERROR_FAIL;
1675 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1676 address,
1677 value);
1679 target_buffer_set_u32(target, value_buf, value);
1680 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1682 LOG_DEBUG("failed: %i", retval);
1685 return retval;
1688 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1690 int retval;
1691 uint8_t value_buf[2];
1692 if (!target_was_examined(target))
1694 LOG_ERROR("Target not examined yet");
1695 return ERROR_FAIL;
1698 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1699 address,
1700 value);
1702 target_buffer_set_u16(target, value_buf, value);
1703 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1705 LOG_DEBUG("failed: %i", retval);
1708 return retval;
1711 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1713 int retval;
1714 if (!target_was_examined(target))
1716 LOG_ERROR("Target not examined yet");
1717 return ERROR_FAIL;
1720 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1721 address, value);
1723 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1725 LOG_DEBUG("failed: %i", retval);
1728 return retval;
1731 COMMAND_HANDLER(handle_targets_command)
1733 struct target *target = all_targets;
1735 if (CMD_ARGC == 1)
1737 target = get_target(CMD_ARGV[0]);
1738 if (target == NULL) {
1739 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1740 goto DumpTargets;
1742 if (!target->tap->enabled) {
1743 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1744 "can't be the current target\n",
1745 target->tap->dotted_name);
1746 return ERROR_FAIL;
1749 CMD_CTX->current_target = target->target_number;
1750 return ERROR_OK;
1752 DumpTargets:
1754 target = all_targets;
1755 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1756 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1757 while (target)
1759 const char *state;
1760 char marker = ' ';
1762 if (target->tap->enabled)
1763 state = target_state_name( target );
1764 else
1765 state = "tap-disabled";
1767 if (CMD_CTX->current_target == target->target_number)
1768 marker = '*';
1770 /* keep columns lined up to match the headers above */
1771 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1772 target->target_number,
1773 marker,
1774 target_name(target),
1775 target_type_name(target),
1776 Jim_Nvp_value2name_simple(nvp_target_endian,
1777 target->endianness)->name,
1778 target->tap->dotted_name,
1779 state);
1780 target = target->next;
1783 return ERROR_OK;
1786 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1788 static int powerDropout;
1789 static int srstAsserted;
1791 static int runPowerRestore;
1792 static int runPowerDropout;
1793 static int runSrstAsserted;
1794 static int runSrstDeasserted;
1796 static int sense_handler(void)
1798 static int prevSrstAsserted = 0;
1799 static int prevPowerdropout = 0;
1801 int retval;
1802 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1803 return retval;
1805 int powerRestored;
1806 powerRestored = prevPowerdropout && !powerDropout;
1807 if (powerRestored)
1809 runPowerRestore = 1;
1812 long long current = timeval_ms();
1813 static long long lastPower = 0;
1814 int waitMore = lastPower + 2000 > current;
1815 if (powerDropout && !waitMore)
1817 runPowerDropout = 1;
1818 lastPower = current;
1821 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1822 return retval;
1824 int srstDeasserted;
1825 srstDeasserted = prevSrstAsserted && !srstAsserted;
1827 static long long lastSrst = 0;
1828 waitMore = lastSrst + 2000 > current;
1829 if (srstDeasserted && !waitMore)
1831 runSrstDeasserted = 1;
1832 lastSrst = current;
1835 if (!prevSrstAsserted && srstAsserted)
1837 runSrstAsserted = 1;
1840 prevSrstAsserted = srstAsserted;
1841 prevPowerdropout = powerDropout;
1843 if (srstDeasserted || powerRestored)
1845 /* Other than logging the event we can't do anything here.
1846 * Issuing a reset is a particularly bad idea as we might
1847 * be inside a reset already.
1851 return ERROR_OK;
1854 static int backoff_times = 0;
1855 static int backoff_count = 0;
1857 /* process target state changes */
1858 static int handle_target(void *priv)
1860 Jim_Interp *interp = (Jim_Interp *)priv;
1861 int retval = ERROR_OK;
1863 if (!is_jtag_poll_safe())
1865 /* polling is disabled currently */
1866 return ERROR_OK;
1869 /* we do not want to recurse here... */
1870 static int recursive = 0;
1871 if (! recursive)
1873 recursive = 1;
1874 sense_handler();
1875 /* danger! running these procedures can trigger srst assertions and power dropouts.
1876 * We need to avoid an infinite loop/recursion here and we do that by
1877 * clearing the flags after running these events.
1879 int did_something = 0;
1880 if (runSrstAsserted)
1882 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1883 Jim_Eval(interp, "srst_asserted");
1884 did_something = 1;
1886 if (runSrstDeasserted)
1888 Jim_Eval(interp, "srst_deasserted");
1889 did_something = 1;
1891 if (runPowerDropout)
1893 LOG_INFO("Power dropout detected, running power_dropout proc.");
1894 Jim_Eval(interp, "power_dropout");
1895 did_something = 1;
1897 if (runPowerRestore)
1899 Jim_Eval(interp, "power_restore");
1900 did_something = 1;
1903 if (did_something)
1905 /* clear detect flags */
1906 sense_handler();
1909 /* clear action flags */
1911 runSrstAsserted = 0;
1912 runSrstDeasserted = 0;
1913 runPowerRestore = 0;
1914 runPowerDropout = 0;
1916 recursive = 0;
1919 if (backoff_times > backoff_count)
1921 /* do not poll this time as we failed previously */
1922 backoff_count++;
1923 return ERROR_OK;
1925 backoff_count = 0;
1927 /* Poll targets for state changes unless that's globally disabled.
1928 * Skip targets that are currently disabled.
1930 for (struct target *target = all_targets;
1931 is_jtag_poll_safe() && target;
1932 target = target->next)
1934 if (!target->tap->enabled)
1935 continue;
1937 /* only poll target if we've got power and srst isn't asserted */
1938 if (!powerDropout && !srstAsserted)
1940 /* polling may fail silently until the target has been examined */
1941 if ((retval = target_poll(target)) != ERROR_OK)
1943 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1944 if (backoff_times * polling_interval < 5000)
1946 backoff_times *= 2;
1947 backoff_times++;
1949 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1951 /* Tell GDB to halt the debugger. This allows the user to
1952 * run monitor commands to handle the situation.
1954 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1955 return retval;
1957 /* Since we succeeded, we reset backoff count */
1958 if (backoff_times > 0)
1960 LOG_USER("Polling succeeded again");
1962 backoff_times = 0;
1966 return retval;
1969 COMMAND_HANDLER(handle_reg_command)
1971 struct target *target;
1972 struct reg *reg = NULL;
1973 unsigned count = 0;
1974 char *value;
1976 LOG_DEBUG("-");
1978 target = get_current_target(CMD_CTX);
1980 /* list all available registers for the current target */
1981 if (CMD_ARGC == 0)
1983 struct reg_cache *cache = target->reg_cache;
1985 count = 0;
1986 while (cache)
1988 unsigned i;
1990 command_print(CMD_CTX, "===== %s", cache->name);
1992 for (i = 0, reg = cache->reg_list;
1993 i < cache->num_regs;
1994 i++, reg++, count++)
1996 /* only print cached values if they are valid */
1997 if (reg->valid) {
1998 value = buf_to_str(reg->value,
1999 reg->size, 16);
2000 command_print(CMD_CTX,
2001 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2002 count, reg->name,
2003 reg->size, value,
2004 reg->dirty
2005 ? " (dirty)"
2006 : "");
2007 free(value);
2008 } else {
2009 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2010 count, reg->name,
2011 reg->size) ;
2014 cache = cache->next;
2017 return ERROR_OK;
2020 /* access a single register by its ordinal number */
2021 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
2023 unsigned num;
2024 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2026 struct reg_cache *cache = target->reg_cache;
2027 count = 0;
2028 while (cache)
2030 unsigned i;
2031 for (i = 0; i < cache->num_regs; i++)
2033 if (count++ == num)
2035 reg = &cache->reg_list[i];
2036 break;
2039 if (reg)
2040 break;
2041 cache = cache->next;
2044 if (!reg)
2046 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2047 return ERROR_OK;
2049 } else /* access a single register by its name */
2051 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2053 if (!reg)
2055 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2056 return ERROR_OK;
2060 /* display a register */
2061 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2063 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2064 reg->valid = 0;
2066 if (reg->valid == 0)
2068 reg->type->get(reg);
2070 value = buf_to_str(reg->value, reg->size, 16);
2071 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2072 free(value);
2073 return ERROR_OK;
2076 /* set register value */
2077 if (CMD_ARGC == 2)
2079 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2080 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2082 reg->type->set(reg, buf);
2084 value = buf_to_str(reg->value, reg->size, 16);
2085 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2086 free(value);
2088 free(buf);
2090 return ERROR_OK;
2093 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2095 return ERROR_OK;
2098 COMMAND_HANDLER(handle_poll_command)
2100 int retval = ERROR_OK;
2101 struct target *target = get_current_target(CMD_CTX);
2103 if (CMD_ARGC == 0)
2105 command_print(CMD_CTX, "background polling: %s",
2106 jtag_poll_get_enabled() ? "on" : "off");
2107 command_print(CMD_CTX, "TAP: %s (%s)",
2108 target->tap->dotted_name,
2109 target->tap->enabled ? "enabled" : "disabled");
2110 if (!target->tap->enabled)
2111 return ERROR_OK;
2112 if ((retval = target_poll(target)) != ERROR_OK)
2113 return retval;
2114 if ((retval = target_arch_state(target)) != ERROR_OK)
2115 return retval;
2117 else if (CMD_ARGC == 1)
2119 bool enable;
2120 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2121 jtag_poll_set_enabled(enable);
2123 else
2125 return ERROR_COMMAND_SYNTAX_ERROR;
2128 return retval;
2131 COMMAND_HANDLER(handle_wait_halt_command)
2133 if (CMD_ARGC > 1)
2134 return ERROR_COMMAND_SYNTAX_ERROR;
2136 unsigned ms = 5000;
2137 if (1 == CMD_ARGC)
2139 int retval = parse_uint(CMD_ARGV[0], &ms);
2140 if (ERROR_OK != retval)
2142 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2143 return ERROR_COMMAND_SYNTAX_ERROR;
2145 // convert seconds (given) to milliseconds (needed)
2146 ms *= 1000;
2149 struct target *target = get_current_target(CMD_CTX);
2150 return target_wait_state(target, TARGET_HALTED, ms);
2153 /* wait for target state to change. The trick here is to have a low
2154 * latency for short waits and not to suck up all the CPU time
2155 * on longer waits.
2157 * After 500ms, keep_alive() is invoked
2159 int target_wait_state(struct target *target, enum target_state state, int ms)
2161 int retval;
2162 long long then = 0, cur;
2163 int once = 1;
2165 for (;;)
2167 if ((retval = target_poll(target)) != ERROR_OK)
2168 return retval;
2169 if (target->state == state)
2171 break;
2173 cur = timeval_ms();
2174 if (once)
2176 once = 0;
2177 then = timeval_ms();
2178 LOG_DEBUG("waiting for target %s...",
2179 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2182 if (cur-then > 500)
2184 keep_alive();
2187 if ((cur-then) > ms)
2189 LOG_ERROR("timed out while waiting for target %s",
2190 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2191 return ERROR_FAIL;
2195 return ERROR_OK;
2198 COMMAND_HANDLER(handle_halt_command)
2200 LOG_DEBUG("-");
2202 struct target *target = get_current_target(CMD_CTX);
2203 int retval = target_halt(target);
2204 if (ERROR_OK != retval)
2205 return retval;
2207 if (CMD_ARGC == 1)
2209 unsigned wait_local;
2210 retval = parse_uint(CMD_ARGV[0], &wait_local);
2211 if (ERROR_OK != retval)
2212 return ERROR_COMMAND_SYNTAX_ERROR;
2213 if (!wait_local)
2214 return ERROR_OK;
2217 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2220 COMMAND_HANDLER(handle_soft_reset_halt_command)
2222 struct target *target = get_current_target(CMD_CTX);
2224 LOG_USER("requesting target halt and executing a soft reset");
2226 target->type->soft_reset_halt(target);
2228 return ERROR_OK;
2231 COMMAND_HANDLER(handle_reset_command)
2233 if (CMD_ARGC > 1)
2234 return ERROR_COMMAND_SYNTAX_ERROR;
2236 enum target_reset_mode reset_mode = RESET_RUN;
2237 if (CMD_ARGC == 1)
2239 const Jim_Nvp *n;
2240 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2241 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2242 return ERROR_COMMAND_SYNTAX_ERROR;
2244 reset_mode = n->value;
2247 /* reset *all* targets */
2248 return target_process_reset(CMD_CTX, reset_mode);
2252 COMMAND_HANDLER(handle_resume_command)
2254 int current = 1;
2255 if (CMD_ARGC > 1)
2256 return ERROR_COMMAND_SYNTAX_ERROR;
2258 struct target *target = get_current_target(CMD_CTX);
2259 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2261 /* with no CMD_ARGV, resume from current pc, addr = 0,
2262 * with one arguments, addr = CMD_ARGV[0],
2263 * handle breakpoints, not debugging */
2264 uint32_t addr = 0;
2265 if (CMD_ARGC == 1)
2267 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2268 current = 0;
2271 return target_resume(target, current, addr, 1, 0);
2274 COMMAND_HANDLER(handle_step_command)
2276 if (CMD_ARGC > 1)
2277 return ERROR_COMMAND_SYNTAX_ERROR;
2279 LOG_DEBUG("-");
2281 /* with no CMD_ARGV, step from current pc, addr = 0,
2282 * with one argument addr = CMD_ARGV[0],
2283 * handle breakpoints, debugging */
2284 uint32_t addr = 0;
2285 int current_pc = 1;
2286 if (CMD_ARGC == 1)
2288 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2289 current_pc = 0;
2292 struct target *target = get_current_target(CMD_CTX);
2294 return target->type->step(target, current_pc, addr, 1);
2297 static void handle_md_output(struct command_context *cmd_ctx,
2298 struct target *target, uint32_t address, unsigned size,
2299 unsigned count, const uint8_t *buffer)
2301 const unsigned line_bytecnt = 32;
2302 unsigned line_modulo = line_bytecnt / size;
2304 char output[line_bytecnt * 4 + 1];
2305 unsigned output_len = 0;
2307 const char *value_fmt;
2308 switch (size) {
2309 case 4: value_fmt = "%8.8x "; break;
2310 case 2: value_fmt = "%4.4x "; break;
2311 case 1: value_fmt = "%2.2x "; break;
2312 default:
2313 /* "can't happen", caller checked */
2314 LOG_ERROR("invalid memory read size: %u", size);
2315 return;
2318 for (unsigned i = 0; i < count; i++)
2320 if (i % line_modulo == 0)
2322 output_len += snprintf(output + output_len,
2323 sizeof(output) - output_len,
2324 "0x%8.8x: ",
2325 (unsigned)(address + (i*size)));
2328 uint32_t value = 0;
2329 const uint8_t *value_ptr = buffer + i * size;
2330 switch (size) {
2331 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2332 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2333 case 1: value = *value_ptr;
2335 output_len += snprintf(output + output_len,
2336 sizeof(output) - output_len,
2337 value_fmt, value);
2339 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2341 command_print(cmd_ctx, "%s", output);
2342 output_len = 0;
2347 COMMAND_HANDLER(handle_md_command)
2349 if (CMD_ARGC < 1)
2350 return ERROR_COMMAND_SYNTAX_ERROR;
2352 unsigned size = 0;
2353 switch (CMD_NAME[2]) {
2354 case 'w': size = 4; break;
2355 case 'h': size = 2; break;
2356 case 'b': size = 1; break;
2357 default: return ERROR_COMMAND_SYNTAX_ERROR;
2360 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2361 int (*fn)(struct target *target,
2362 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2363 if (physical)
2365 CMD_ARGC--;
2366 CMD_ARGV++;
2367 fn=target_read_phys_memory;
2368 } else
2370 fn=target_read_memory;
2372 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2374 return ERROR_COMMAND_SYNTAX_ERROR;
2377 uint32_t address;
2378 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2380 unsigned count = 1;
2381 if (CMD_ARGC == 2)
2382 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2384 uint8_t *buffer = calloc(count, size);
2386 struct target *target = get_current_target(CMD_CTX);
2387 int retval = fn(target, address, size, count, buffer);
2388 if (ERROR_OK == retval)
2389 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2391 free(buffer);
2393 return retval;
2396 typedef int (*target_write_fn)(struct target *target,
2397 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2399 static int target_write_memory_fast(struct target *target,
2400 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2402 return target_write_buffer(target, address, size * count, buffer);
2405 static int target_fill_mem(struct target *target,
2406 uint32_t address,
2407 target_write_fn fn,
2408 unsigned data_size,
2409 /* value */
2410 uint32_t b,
2411 /* count */
2412 unsigned c)
2414 /* We have to write in reasonably large chunks to be able
2415 * to fill large memory areas with any sane speed */
2416 const unsigned chunk_size = 16384;
2417 uint8_t *target_buf = malloc(chunk_size * data_size);
2418 if (target_buf == NULL)
2420 LOG_ERROR("Out of memory");
2421 return ERROR_FAIL;
2424 for (unsigned i = 0; i < chunk_size; i ++)
2426 switch (data_size)
2428 case 4:
2429 target_buffer_set_u32(target, target_buf + i*data_size, b);
2430 break;
2431 case 2:
2432 target_buffer_set_u16(target, target_buf + i*data_size, b);
2433 break;
2434 case 1:
2435 target_buffer_set_u8(target, target_buf + i*data_size, b);
2436 break;
2437 default:
2438 exit(-1);
2442 int retval = ERROR_OK;
2444 for (unsigned x = 0; x < c; x += chunk_size)
2446 unsigned current;
2447 current = c - x;
2448 if (current > chunk_size)
2450 current = chunk_size;
2452 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2453 if (retval != ERROR_OK)
2455 break;
2457 /* avoid GDB timeouts */
2458 keep_alive();
2460 free(target_buf);
2462 return retval;
2466 COMMAND_HANDLER(handle_mw_command)
2468 if (CMD_ARGC < 2)
2470 return ERROR_COMMAND_SYNTAX_ERROR;
2472 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2473 target_write_fn fn;
2474 if (physical)
2476 CMD_ARGC--;
2477 CMD_ARGV++;
2478 fn=target_write_phys_memory;
2479 } else
2481 fn = target_write_memory_fast;
2483 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2484 return ERROR_COMMAND_SYNTAX_ERROR;
2486 uint32_t address;
2487 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2489 uint32_t value;
2490 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2492 unsigned count = 1;
2493 if (CMD_ARGC == 3)
2494 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2496 struct target *target = get_current_target(CMD_CTX);
2497 unsigned wordsize;
2498 switch (CMD_NAME[2])
2500 case 'w':
2501 wordsize = 4;
2502 break;
2503 case 'h':
2504 wordsize = 2;
2505 break;
2506 case 'b':
2507 wordsize = 1;
2508 break;
2509 default:
2510 return ERROR_COMMAND_SYNTAX_ERROR;
2513 return target_fill_mem(target, address, fn, wordsize, value, count);
2516 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2517 uint32_t *min_address, uint32_t *max_address)
2519 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2520 return ERROR_COMMAND_SYNTAX_ERROR;
2522 /* a base address isn't always necessary,
2523 * default to 0x0 (i.e. don't relocate) */
2524 if (CMD_ARGC >= 2)
2526 uint32_t addr;
2527 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2528 image->base_address = addr;
2529 image->base_address_set = 1;
2531 else
2532 image->base_address_set = 0;
2534 image->start_address_set = 0;
2536 if (CMD_ARGC >= 4)
2538 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2540 if (CMD_ARGC == 5)
2542 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2543 // use size (given) to find max (required)
2544 *max_address += *min_address;
2547 if (*min_address > *max_address)
2548 return ERROR_COMMAND_SYNTAX_ERROR;
2550 return ERROR_OK;
2553 COMMAND_HANDLER(handle_load_image_command)
2555 uint8_t *buffer;
2556 size_t buf_cnt;
2557 uint32_t image_size;
2558 uint32_t min_address = 0;
2559 uint32_t max_address = 0xffffffff;
2560 int i;
2561 struct image image;
2563 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2564 &image, &min_address, &max_address);
2565 if (ERROR_OK != retval)
2566 return retval;
2568 struct target *target = get_current_target(CMD_CTX);
2570 struct duration bench;
2571 duration_start(&bench);
2573 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2575 return ERROR_OK;
2578 image_size = 0x0;
2579 retval = ERROR_OK;
2580 for (i = 0; i < image.num_sections; i++)
2582 buffer = malloc(image.sections[i].size);
2583 if (buffer == NULL)
2585 command_print(CMD_CTX,
2586 "error allocating buffer for section (%d bytes)",
2587 (int)(image.sections[i].size));
2588 break;
2591 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2593 free(buffer);
2594 break;
2597 uint32_t offset = 0;
2598 uint32_t length = buf_cnt;
2600 /* DANGER!!! beware of unsigned comparision here!!! */
2602 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2603 (image.sections[i].base_address < max_address))
2605 if (image.sections[i].base_address < min_address)
2607 /* clip addresses below */
2608 offset += min_address-image.sections[i].base_address;
2609 length -= offset;
2612 if (image.sections[i].base_address + buf_cnt > max_address)
2614 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2617 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2619 free(buffer);
2620 break;
2622 image_size += length;
2623 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2624 (unsigned int)length,
2625 image.sections[i].base_address + offset);
2628 free(buffer);
2631 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2633 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2634 "in %fs (%0.3f KiB/s)", image_size,
2635 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2638 image_close(&image);
2640 return retval;
2644 COMMAND_HANDLER(handle_dump_image_command)
2646 struct fileio fileio;
2647 uint8_t buffer[560];
2648 int retval, retvaltemp;
2649 uint32_t address, size;
2650 struct duration bench;
2651 struct target *target = get_current_target(CMD_CTX);
2653 if (CMD_ARGC != 3)
2654 return ERROR_COMMAND_SYNTAX_ERROR;
2656 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2657 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2659 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2660 if (retval != ERROR_OK)
2661 return retval;
2663 duration_start(&bench);
2665 retval = ERROR_OK;
2666 while (size > 0)
2668 size_t size_written;
2669 uint32_t this_run_size = (size > 560) ? 560 : size;
2670 retval = target_read_buffer(target, address, this_run_size, buffer);
2671 if (retval != ERROR_OK)
2673 break;
2676 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2677 if (retval != ERROR_OK)
2679 break;
2682 size -= this_run_size;
2683 address += this_run_size;
2686 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2688 int filesize;
2689 retval = fileio_size(&fileio, &filesize);
2690 if (retval != ERROR_OK)
2691 return retval;
2692 command_print(CMD_CTX,
2693 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2694 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2697 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2698 return retvaltemp;
2700 return retval;
2703 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2705 uint8_t *buffer;
2706 size_t buf_cnt;
2707 uint32_t image_size;
2708 int i;
2709 int retval;
2710 uint32_t checksum = 0;
2711 uint32_t mem_checksum = 0;
2713 struct image image;
2715 struct target *target = get_current_target(CMD_CTX);
2717 if (CMD_ARGC < 1)
2719 return ERROR_COMMAND_SYNTAX_ERROR;
2722 if (!target)
2724 LOG_ERROR("no target selected");
2725 return ERROR_FAIL;
2728 struct duration bench;
2729 duration_start(&bench);
2731 if (CMD_ARGC >= 2)
2733 uint32_t addr;
2734 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2735 image.base_address = addr;
2736 image.base_address_set = 1;
2738 else
2740 image.base_address_set = 0;
2741 image.base_address = 0x0;
2744 image.start_address_set = 0;
2746 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2748 return retval;
2751 image_size = 0x0;
2752 int diffs = 0;
2753 retval = ERROR_OK;
2754 for (i = 0; i < image.num_sections; i++)
2756 buffer = malloc(image.sections[i].size);
2757 if (buffer == NULL)
2759 command_print(CMD_CTX,
2760 "error allocating buffer for section (%d bytes)",
2761 (int)(image.sections[i].size));
2762 break;
2764 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2766 free(buffer);
2767 break;
2770 if (verify)
2772 /* calculate checksum of image */
2773 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2774 if (retval != ERROR_OK)
2776 free(buffer);
2777 break;
2780 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2781 if (retval != ERROR_OK)
2783 free(buffer);
2784 break;
2787 if (checksum != mem_checksum)
2789 /* failed crc checksum, fall back to a binary compare */
2790 uint8_t *data;
2792 if (diffs == 0)
2794 LOG_ERROR("checksum mismatch - attempting binary compare");
2797 data = (uint8_t*)malloc(buf_cnt);
2799 /* Can we use 32bit word accesses? */
2800 int size = 1;
2801 int count = buf_cnt;
2802 if ((count % 4) == 0)
2804 size *= 4;
2805 count /= 4;
2807 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2808 if (retval == ERROR_OK)
2810 uint32_t t;
2811 for (t = 0; t < buf_cnt; t++)
2813 if (data[t] != buffer[t])
2815 command_print(CMD_CTX,
2816 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2817 diffs,
2818 (unsigned)(t + image.sections[i].base_address),
2819 data[t],
2820 buffer[t]);
2821 if (diffs++ >= 127)
2823 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2824 free(data);
2825 free(buffer);
2826 goto done;
2829 keep_alive();
2832 free(data);
2834 } else
2836 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2837 image.sections[i].base_address,
2838 buf_cnt);
2841 free(buffer);
2842 image_size += buf_cnt;
2844 if (diffs > 0)
2846 command_print(CMD_CTX, "No more differences found.");
2848 done:
2849 if (diffs > 0)
2851 retval = ERROR_FAIL;
2853 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2855 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2856 "in %fs (%0.3f KiB/s)", image_size,
2857 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2860 image_close(&image);
2862 return retval;
2865 COMMAND_HANDLER(handle_verify_image_command)
2867 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2870 COMMAND_HANDLER(handle_test_image_command)
2872 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2875 static int handle_bp_command_list(struct command_context *cmd_ctx)
2877 struct target *target = get_current_target(cmd_ctx);
2878 struct breakpoint *breakpoint = target->breakpoints;
2879 while (breakpoint)
2881 if (breakpoint->type == BKPT_SOFT)
2883 char* buf = buf_to_str(breakpoint->orig_instr,
2884 breakpoint->length, 16);
2885 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2886 breakpoint->address,
2887 breakpoint->length,
2888 breakpoint->set, buf);
2889 free(buf);
2891 else
2893 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2894 breakpoint->address,
2895 breakpoint->length, breakpoint->set);
2898 breakpoint = breakpoint->next;
2900 return ERROR_OK;
2903 static int handle_bp_command_set(struct command_context *cmd_ctx,
2904 uint32_t addr, uint32_t length, int hw)
2906 struct target *target = get_current_target(cmd_ctx);
2907 int retval = breakpoint_add(target, addr, length, hw);
2908 if (ERROR_OK == retval)
2909 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2910 else
2911 LOG_ERROR("Failure setting breakpoint");
2912 return retval;
2915 COMMAND_HANDLER(handle_bp_command)
2917 if (CMD_ARGC == 0)
2918 return handle_bp_command_list(CMD_CTX);
2920 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2922 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2923 return ERROR_COMMAND_SYNTAX_ERROR;
2926 uint32_t addr;
2927 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2928 uint32_t length;
2929 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2931 int hw = BKPT_SOFT;
2932 if (CMD_ARGC == 3)
2934 if (strcmp(CMD_ARGV[2], "hw") == 0)
2935 hw = BKPT_HARD;
2936 else
2937 return ERROR_COMMAND_SYNTAX_ERROR;
2940 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2943 COMMAND_HANDLER(handle_rbp_command)
2945 if (CMD_ARGC != 1)
2946 return ERROR_COMMAND_SYNTAX_ERROR;
2948 uint32_t addr;
2949 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2951 struct target *target = get_current_target(CMD_CTX);
2952 breakpoint_remove(target, addr);
2954 return ERROR_OK;
2957 COMMAND_HANDLER(handle_wp_command)
2959 struct target *target = get_current_target(CMD_CTX);
2961 if (CMD_ARGC == 0)
2963 struct watchpoint *watchpoint = target->watchpoints;
2965 while (watchpoint)
2967 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2968 ", len: 0x%8.8" PRIx32
2969 ", r/w/a: %i, value: 0x%8.8" PRIx32
2970 ", mask: 0x%8.8" PRIx32,
2971 watchpoint->address,
2972 watchpoint->length,
2973 (int)watchpoint->rw,
2974 watchpoint->value,
2975 watchpoint->mask);
2976 watchpoint = watchpoint->next;
2978 return ERROR_OK;
2981 enum watchpoint_rw type = WPT_ACCESS;
2982 uint32_t addr = 0;
2983 uint32_t length = 0;
2984 uint32_t data_value = 0x0;
2985 uint32_t data_mask = 0xffffffff;
2987 switch (CMD_ARGC)
2989 case 5:
2990 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2991 // fall through
2992 case 4:
2993 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2994 // fall through
2995 case 3:
2996 switch (CMD_ARGV[2][0])
2998 case 'r':
2999 type = WPT_READ;
3000 break;
3001 case 'w':
3002 type = WPT_WRITE;
3003 break;
3004 case 'a':
3005 type = WPT_ACCESS;
3006 break;
3007 default:
3008 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3009 return ERROR_COMMAND_SYNTAX_ERROR;
3011 // fall through
3012 case 2:
3013 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3014 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3015 break;
3017 default:
3018 command_print(CMD_CTX, "usage: wp [address length "
3019 "[(r|w|a) [value [mask]]]]");
3020 return ERROR_COMMAND_SYNTAX_ERROR;
3023 int retval = watchpoint_add(target, addr, length, type,
3024 data_value, data_mask);
3025 if (ERROR_OK != retval)
3026 LOG_ERROR("Failure setting watchpoints");
3028 return retval;
3031 COMMAND_HANDLER(handle_rwp_command)
3033 if (CMD_ARGC != 1)
3034 return ERROR_COMMAND_SYNTAX_ERROR;
3036 uint32_t addr;
3037 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3039 struct target *target = get_current_target(CMD_CTX);
3040 watchpoint_remove(target, addr);
3042 return ERROR_OK;
3047 * Translate a virtual address to a physical address.
3049 * The low-level target implementation must have logged a detailed error
3050 * which is forwarded to telnet/GDB session.
3052 COMMAND_HANDLER(handle_virt2phys_command)
3054 if (CMD_ARGC != 1)
3055 return ERROR_COMMAND_SYNTAX_ERROR;
3057 uint32_t va;
3058 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3059 uint32_t pa;
3061 struct target *target = get_current_target(CMD_CTX);
3062 int retval = target->type->virt2phys(target, va, &pa);
3063 if (retval == ERROR_OK)
3064 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3066 return retval;
3069 static void writeData(FILE *f, const void *data, size_t len)
3071 size_t written = fwrite(data, 1, len, f);
3072 if (written != len)
3073 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3076 static void writeLong(FILE *f, int l)
3078 int i;
3079 for (i = 0; i < 4; i++)
3081 char c = (l >> (i*8))&0xff;
3082 writeData(f, &c, 1);
3087 static void writeString(FILE *f, char *s)
3089 writeData(f, s, strlen(s));
3092 /* Dump a gmon.out histogram file. */
3093 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3095 uint32_t i;
3096 FILE *f = fopen(filename, "w");
3097 if (f == NULL)
3098 return;
3099 writeString(f, "gmon");
3100 writeLong(f, 0x00000001); /* Version */
3101 writeLong(f, 0); /* padding */
3102 writeLong(f, 0); /* padding */
3103 writeLong(f, 0); /* padding */
3105 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3106 writeData(f, &zero, 1);
3108 /* figure out bucket size */
3109 uint32_t min = samples[0];
3110 uint32_t max = samples[0];
3111 for (i = 0; i < sampleNum; i++)
3113 if (min > samples[i])
3115 min = samples[i];
3117 if (max < samples[i])
3119 max = samples[i];
3123 int addressSpace = (max-min + 1);
3125 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3126 uint32_t length = addressSpace;
3127 if (length > maxBuckets)
3129 length = maxBuckets;
3131 int *buckets = malloc(sizeof(int)*length);
3132 if (buckets == NULL)
3134 fclose(f);
3135 return;
3137 memset(buckets, 0, sizeof(int)*length);
3138 for (i = 0; i < sampleNum;i++)
3140 uint32_t address = samples[i];
3141 long long a = address-min;
3142 long long b = length-1;
3143 long long c = addressSpace-1;
3144 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3145 buckets[index_t]++;
3148 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3149 writeLong(f, min); /* low_pc */
3150 writeLong(f, max); /* high_pc */
3151 writeLong(f, length); /* # of samples */
3152 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3153 writeString(f, "seconds");
3154 for (i = 0; i < (15-strlen("seconds")); i++)
3155 writeData(f, &zero, 1);
3156 writeString(f, "s");
3158 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3160 char *data = malloc(2*length);
3161 if (data != NULL)
3163 for (i = 0; i < length;i++)
3165 int val;
3166 val = buckets[i];
3167 if (val > 65535)
3169 val = 65535;
3171 data[i*2]=val&0xff;
3172 data[i*2 + 1]=(val >> 8)&0xff;
3174 free(buckets);
3175 writeData(f, data, length * 2);
3176 free(data);
3177 } else
3179 free(buckets);
3182 fclose(f);
3185 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3186 * which will be used as a random sampling of PC */
3187 COMMAND_HANDLER(handle_profile_command)
3189 struct target *target = get_current_target(CMD_CTX);
3190 struct timeval timeout, now;
3192 gettimeofday(&timeout, NULL);
3193 if (CMD_ARGC != 2)
3195 return ERROR_COMMAND_SYNTAX_ERROR;
3197 unsigned offset;
3198 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3200 timeval_add_time(&timeout, offset, 0);
3203 * @todo: Some cores let us sample the PC without the
3204 * annoying halt/resume step; for example, ARMv7 PCSR.
3205 * Provide a way to use that more efficient mechanism.
3208 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3210 static const int maxSample = 10000;
3211 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3212 if (samples == NULL)
3213 return ERROR_OK;
3215 int numSamples = 0;
3216 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3217 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3219 for (;;)
3221 int retval;
3222 target_poll(target);
3223 if (target->state == TARGET_HALTED)
3225 uint32_t t=*((uint32_t *)reg->value);
3226 samples[numSamples++]=t;
3227 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3228 target_poll(target);
3229 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3230 } else if (target->state == TARGET_RUNNING)
3232 /* We want to quickly sample the PC. */
3233 if ((retval = target_halt(target)) != ERROR_OK)
3235 free(samples);
3236 return retval;
3238 } else
3240 command_print(CMD_CTX, "Target not halted or running");
3241 retval = ERROR_OK;
3242 break;
3244 if (retval != ERROR_OK)
3246 break;
3249 gettimeofday(&now, NULL);
3250 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3252 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3253 if ((retval = target_poll(target)) != ERROR_OK)
3255 free(samples);
3256 return retval;
3258 if (target->state == TARGET_HALTED)
3260 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3262 if ((retval = target_poll(target)) != ERROR_OK)
3264 free(samples);
3265 return retval;
3267 writeGmon(samples, numSamples, CMD_ARGV[1]);
3268 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3269 break;
3272 free(samples);
3274 return ERROR_OK;
3277 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3279 char *namebuf;
3280 Jim_Obj *nameObjPtr, *valObjPtr;
3281 int result;
3283 namebuf = alloc_printf("%s(%d)", varname, idx);
3284 if (!namebuf)
3285 return JIM_ERR;
3287 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3288 valObjPtr = Jim_NewIntObj(interp, val);
3289 if (!nameObjPtr || !valObjPtr)
3291 free(namebuf);
3292 return JIM_ERR;
3295 Jim_IncrRefCount(nameObjPtr);
3296 Jim_IncrRefCount(valObjPtr);
3297 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3298 Jim_DecrRefCount(interp, nameObjPtr);
3299 Jim_DecrRefCount(interp, valObjPtr);
3300 free(namebuf);
3301 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3302 return result;
3305 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3307 struct command_context *context;
3308 struct target *target;
3310 context = current_command_context(interp);
3311 assert (context != NULL);
3313 target = get_current_target(context);
3314 if (target == NULL)
3316 LOG_ERROR("mem2array: no current target");
3317 return JIM_ERR;
3320 return target_mem2array(interp, target, argc-1, argv + 1);
3323 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3325 long l;
3326 uint32_t width;
3327 int len;
3328 uint32_t addr;
3329 uint32_t count;
3330 uint32_t v;
3331 const char *varname;
3332 int n, e, retval;
3333 uint32_t i;
3335 /* argv[1] = name of array to receive the data
3336 * argv[2] = desired width
3337 * argv[3] = memory address
3338 * argv[4] = count of times to read
3340 if (argc != 4) {
3341 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3342 return JIM_ERR;
3344 varname = Jim_GetString(argv[0], &len);
3345 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3347 e = Jim_GetLong(interp, argv[1], &l);
3348 width = l;
3349 if (e != JIM_OK) {
3350 return e;
3353 e = Jim_GetLong(interp, argv[2], &l);
3354 addr = l;
3355 if (e != JIM_OK) {
3356 return e;
3358 e = Jim_GetLong(interp, argv[3], &l);
3359 len = l;
3360 if (e != JIM_OK) {
3361 return e;
3363 switch (width) {
3364 case 8:
3365 width = 1;
3366 break;
3367 case 16:
3368 width = 2;
3369 break;
3370 case 32:
3371 width = 4;
3372 break;
3373 default:
3374 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3375 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3376 return JIM_ERR;
3378 if (len == 0) {
3379 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3380 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3381 return JIM_ERR;
3383 if ((addr + (len * width)) < addr) {
3384 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3385 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3386 return JIM_ERR;
3388 /* absurd transfer size? */
3389 if (len > 65536) {
3390 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3391 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3392 return JIM_ERR;
3395 if ((width == 1) ||
3396 ((width == 2) && ((addr & 1) == 0)) ||
3397 ((width == 4) && ((addr & 3) == 0))) {
3398 /* all is well */
3399 } else {
3400 char buf[100];
3401 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3402 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3403 addr,
3404 width);
3405 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3406 return JIM_ERR;
3409 /* Transfer loop */
3411 /* index counter */
3412 n = 0;
3414 size_t buffersize = 4096;
3415 uint8_t *buffer = malloc(buffersize);
3416 if (buffer == NULL)
3417 return JIM_ERR;
3419 /* assume ok */
3420 e = JIM_OK;
3421 while (len) {
3422 /* Slurp... in buffer size chunks */
3424 count = len; /* in objects.. */
3425 if (count > (buffersize/width)) {
3426 count = (buffersize/width);
3429 retval = target_read_memory(target, addr, width, count, buffer);
3430 if (retval != ERROR_OK) {
3431 /* BOO !*/
3432 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3433 (unsigned int)addr,
3434 (int)width,
3435 (int)count);
3436 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3437 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3438 e = JIM_ERR;
3439 len = 0;
3440 } else {
3441 v = 0; /* shut up gcc */
3442 for (i = 0 ;i < count ;i++, n++) {
3443 switch (width) {
3444 case 4:
3445 v = target_buffer_get_u32(target, &buffer[i*width]);
3446 break;
3447 case 2:
3448 v = target_buffer_get_u16(target, &buffer[i*width]);
3449 break;
3450 case 1:
3451 v = buffer[i] & 0x0ff;
3452 break;
3454 new_int_array_element(interp, varname, n, v);
3456 len -= count;
3460 free(buffer);
3462 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3464 return JIM_OK;
3467 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3469 char *namebuf;
3470 Jim_Obj *nameObjPtr, *valObjPtr;
3471 int result;
3472 long l;
3474 namebuf = alloc_printf("%s(%d)", varname, idx);
3475 if (!namebuf)
3476 return JIM_ERR;
3478 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3479 if (!nameObjPtr)
3481 free(namebuf);
3482 return JIM_ERR;
3485 Jim_IncrRefCount(nameObjPtr);
3486 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3487 Jim_DecrRefCount(interp, nameObjPtr);
3488 free(namebuf);
3489 if (valObjPtr == NULL)
3490 return JIM_ERR;
3492 result = Jim_GetLong(interp, valObjPtr, &l);
3493 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3494 *val = l;
3495 return result;
3498 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3500 struct command_context *context;
3501 struct target *target;
3503 context = current_command_context(interp);
3504 assert (context != NULL);
3506 target = get_current_target(context);
3507 if (target == NULL) {
3508 LOG_ERROR("array2mem: no current target");
3509 return JIM_ERR;
3512 return target_array2mem(interp,target, argc-1, argv + 1);
3515 static int target_array2mem(Jim_Interp *interp, struct target *target,
3516 int argc, Jim_Obj *const *argv)
3518 long l;
3519 uint32_t width;
3520 int len;
3521 uint32_t addr;
3522 uint32_t count;
3523 uint32_t v;
3524 const char *varname;
3525 int n, e, retval;
3526 uint32_t i;
3528 /* argv[1] = name of array to get the data
3529 * argv[2] = desired width
3530 * argv[3] = memory address
3531 * argv[4] = count to write
3533 if (argc != 4) {
3534 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3535 return JIM_ERR;
3537 varname = Jim_GetString(argv[0], &len);
3538 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3540 e = Jim_GetLong(interp, argv[1], &l);
3541 width = l;
3542 if (e != JIM_OK) {
3543 return e;
3546 e = Jim_GetLong(interp, argv[2], &l);
3547 addr = l;
3548 if (e != JIM_OK) {
3549 return e;
3551 e = Jim_GetLong(interp, argv[3], &l);
3552 len = l;
3553 if (e != JIM_OK) {
3554 return e;
3556 switch (width) {
3557 case 8:
3558 width = 1;
3559 break;
3560 case 16:
3561 width = 2;
3562 break;
3563 case 32:
3564 width = 4;
3565 break;
3566 default:
3567 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3568 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3569 return JIM_ERR;
3571 if (len == 0) {
3572 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3573 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3574 return JIM_ERR;
3576 if ((addr + (len * width)) < addr) {
3577 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3578 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3579 return JIM_ERR;
3581 /* absurd transfer size? */
3582 if (len > 65536) {
3583 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3584 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3585 return JIM_ERR;
3588 if ((width == 1) ||
3589 ((width == 2) && ((addr & 1) == 0)) ||
3590 ((width == 4) && ((addr & 3) == 0))) {
3591 /* all is well */
3592 } else {
3593 char buf[100];
3594 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3595 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3596 (unsigned int)addr,
3597 (int)width);
3598 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3599 return JIM_ERR;
3602 /* Transfer loop */
3604 /* index counter */
3605 n = 0;
3606 /* assume ok */
3607 e = JIM_OK;
3609 size_t buffersize = 4096;
3610 uint8_t *buffer = malloc(buffersize);
3611 if (buffer == NULL)
3612 return JIM_ERR;
3614 while (len) {
3615 /* Slurp... in buffer size chunks */
3617 count = len; /* in objects.. */
3618 if (count > (buffersize/width)) {
3619 count = (buffersize/width);
3622 v = 0; /* shut up gcc */
3623 for (i = 0 ;i < count ;i++, n++) {
3624 get_int_array_element(interp, varname, n, &v);
3625 switch (width) {
3626 case 4:
3627 target_buffer_set_u32(target, &buffer[i*width], v);
3628 break;
3629 case 2:
3630 target_buffer_set_u16(target, &buffer[i*width], v);
3631 break;
3632 case 1:
3633 buffer[i] = v & 0x0ff;
3634 break;
3637 len -= count;
3639 retval = target_write_memory(target, addr, width, count, buffer);
3640 if (retval != ERROR_OK) {
3641 /* BOO !*/
3642 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3643 (unsigned int)addr,
3644 (int)width,
3645 (int)count);
3646 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3647 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3648 e = JIM_ERR;
3649 len = 0;
3653 free(buffer);
3655 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3657 return JIM_OK;
3660 /* FIX? should we propagate errors here rather than printing them
3661 * and continuing?
3663 void target_handle_event(struct target *target, enum target_event e)
3665 struct target_event_action *teap;
3667 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3668 if (teap->event == e) {
3669 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3670 target->target_number,
3671 target_name(target),
3672 target_type_name(target),
3674 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3675 Jim_GetString(teap->body, NULL));
3676 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3678 Jim_MakeErrorMessage(teap->interp);
3679 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3686 * Returns true only if the target has a handler for the specified event.
3688 bool target_has_event_action(struct target *target, enum target_event event)
3690 struct target_event_action *teap;
3692 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3693 if (teap->event == event)
3694 return true;
3696 return false;
3699 enum target_cfg_param {
3700 TCFG_TYPE,
3701 TCFG_EVENT,
3702 TCFG_WORK_AREA_VIRT,
3703 TCFG_WORK_AREA_PHYS,
3704 TCFG_WORK_AREA_SIZE,
3705 TCFG_WORK_AREA_BACKUP,
3706 TCFG_ENDIAN,
3707 TCFG_VARIANT,
3708 TCFG_COREID,
3709 TCFG_CHAIN_POSITION,
3710 TCFG_DBGBASE,
3711 TCFG_RTOS,
3714 static Jim_Nvp nvp_config_opts[] = {
3715 { .name = "-type", .value = TCFG_TYPE },
3716 { .name = "-event", .value = TCFG_EVENT },
3717 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3718 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3719 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3720 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3721 { .name = "-endian" , .value = TCFG_ENDIAN },
3722 { .name = "-variant", .value = TCFG_VARIANT },
3723 { .name = "-coreid", .value = TCFG_COREID },
3724 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3725 { .name = "-dbgbase", .value = TCFG_DBGBASE },
3726 { .name = "-rtos", .value = TCFG_RTOS },
3727 { .name = NULL, .value = -1 }
3730 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3732 Jim_Nvp *n;
3733 Jim_Obj *o;
3734 jim_wide w;
3735 char *cp;
3736 int e;
3738 /* parse config or cget options ... */
3739 while (goi->argc > 0) {
3740 Jim_SetEmptyResult(goi->interp);
3741 /* Jim_GetOpt_Debug(goi); */
3743 if (target->type->target_jim_configure) {
3744 /* target defines a configure function */
3745 /* target gets first dibs on parameters */
3746 e = (*(target->type->target_jim_configure))(target, goi);
3747 if (e == JIM_OK) {
3748 /* more? */
3749 continue;
3751 if (e == JIM_ERR) {
3752 /* An error */
3753 return e;
3755 /* otherwise we 'continue' below */
3757 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3758 if (e != JIM_OK) {
3759 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3760 return e;
3762 switch (n->value) {
3763 case TCFG_TYPE:
3764 /* not setable */
3765 if (goi->isconfigure) {
3766 Jim_SetResultFormatted(goi->interp,
3767 "not settable: %s", n->name);
3768 return JIM_ERR;
3769 } else {
3770 no_params:
3771 if (goi->argc != 0) {
3772 Jim_WrongNumArgs(goi->interp,
3773 goi->argc, goi->argv,
3774 "NO PARAMS");
3775 return JIM_ERR;
3778 Jim_SetResultString(goi->interp,
3779 target_type_name(target), -1);
3780 /* loop for more */
3781 break;
3782 case TCFG_EVENT:
3783 if (goi->argc == 0) {
3784 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3785 return JIM_ERR;
3788 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3789 if (e != JIM_OK) {
3790 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3791 return e;
3794 if (goi->isconfigure) {
3795 if (goi->argc != 1) {
3796 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3797 return JIM_ERR;
3799 } else {
3800 if (goi->argc != 0) {
3801 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3802 return JIM_ERR;
3807 struct target_event_action *teap;
3809 teap = target->event_action;
3810 /* replace existing? */
3811 while (teap) {
3812 if (teap->event == (enum target_event)n->value) {
3813 break;
3815 teap = teap->next;
3818 if (goi->isconfigure) {
3819 bool replace = true;
3820 if (teap == NULL) {
3821 /* create new */
3822 teap = calloc(1, sizeof(*teap));
3823 replace = false;
3825 teap->event = n->value;
3826 teap->interp = goi->interp;
3827 Jim_GetOpt_Obj(goi, &o);
3828 if (teap->body) {
3829 Jim_DecrRefCount(teap->interp, teap->body);
3831 teap->body = Jim_DuplicateObj(goi->interp, o);
3833 * FIXME:
3834 * Tcl/TK - "tk events" have a nice feature.
3835 * See the "BIND" command.
3836 * We should support that here.
3837 * You can specify %X and %Y in the event code.
3838 * The idea is: %T - target name.
3839 * The idea is: %N - target number
3840 * The idea is: %E - event name.
3842 Jim_IncrRefCount(teap->body);
3844 if (!replace)
3846 /* add to head of event list */
3847 teap->next = target->event_action;
3848 target->event_action = teap;
3850 Jim_SetEmptyResult(goi->interp);
3851 } else {
3852 /* get */
3853 if (teap == NULL) {
3854 Jim_SetEmptyResult(goi->interp);
3855 } else {
3856 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3860 /* loop for more */
3861 break;
3863 case TCFG_WORK_AREA_VIRT:
3864 if (goi->isconfigure) {
3865 target_free_all_working_areas(target);
3866 e = Jim_GetOpt_Wide(goi, &w);
3867 if (e != JIM_OK) {
3868 return e;
3870 target->working_area_virt = w;
3871 target->working_area_virt_spec = true;
3872 } else {
3873 if (goi->argc != 0) {
3874 goto no_params;
3877 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3878 /* loop for more */
3879 break;
3881 case TCFG_WORK_AREA_PHYS:
3882 if (goi->isconfigure) {
3883 target_free_all_working_areas(target);
3884 e = Jim_GetOpt_Wide(goi, &w);
3885 if (e != JIM_OK) {
3886 return e;
3888 target->working_area_phys = w;
3889 target->working_area_phys_spec = true;
3890 } else {
3891 if (goi->argc != 0) {
3892 goto no_params;
3895 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3896 /* loop for more */
3897 break;
3899 case TCFG_WORK_AREA_SIZE:
3900 if (goi->isconfigure) {
3901 target_free_all_working_areas(target);
3902 e = Jim_GetOpt_Wide(goi, &w);
3903 if (e != JIM_OK) {
3904 return e;
3906 target->working_area_size = w;
3907 } else {
3908 if (goi->argc != 0) {
3909 goto no_params;
3912 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3913 /* loop for more */
3914 break;
3916 case TCFG_WORK_AREA_BACKUP:
3917 if (goi->isconfigure) {
3918 target_free_all_working_areas(target);
3919 e = Jim_GetOpt_Wide(goi, &w);
3920 if (e != JIM_OK) {
3921 return e;
3923 /* make this exactly 1 or 0 */
3924 target->backup_working_area = (!!w);
3925 } else {
3926 if (goi->argc != 0) {
3927 goto no_params;
3930 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3931 /* loop for more e*/
3932 break;
3934 case TCFG_ENDIAN:
3935 if (goi->isconfigure) {
3936 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3937 if (e != JIM_OK) {
3938 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3939 return e;
3941 target->endianness = n->value;
3942 } else {
3943 if (goi->argc != 0) {
3944 goto no_params;
3947 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3948 if (n->name == NULL) {
3949 target->endianness = TARGET_LITTLE_ENDIAN;
3950 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3952 Jim_SetResultString(goi->interp, n->name, -1);
3953 /* loop for more */
3954 break;
3956 case TCFG_VARIANT:
3957 if (goi->isconfigure) {
3958 if (goi->argc < 1) {
3959 Jim_SetResultFormatted(goi->interp,
3960 "%s ?STRING?",
3961 n->name);
3962 return JIM_ERR;
3964 if (target->variant) {
3965 free((void *)(target->variant));
3967 e = Jim_GetOpt_String(goi, &cp, NULL);
3968 target->variant = strdup(cp);
3969 } else {
3970 if (goi->argc != 0) {
3971 goto no_params;
3974 Jim_SetResultString(goi->interp, target->variant,-1);
3975 /* loop for more */
3976 break;
3978 case TCFG_COREID:
3979 if (goi->isconfigure) {
3980 e = Jim_GetOpt_Wide(goi, &w);
3981 if (e != JIM_OK) {
3982 return e;
3984 target->coreid = (int)w;
3985 } else {
3986 if (goi->argc != 0) {
3987 goto no_params;
3990 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3991 /* loop for more */
3992 break;
3994 case TCFG_CHAIN_POSITION:
3995 if (goi->isconfigure) {
3996 Jim_Obj *o_t;
3997 struct jtag_tap *tap;
3998 target_free_all_working_areas(target);
3999 e = Jim_GetOpt_Obj(goi, &o_t);
4000 if (e != JIM_OK) {
4001 return e;
4003 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4004 if (tap == NULL) {
4005 return JIM_ERR;
4007 /* make this exactly 1 or 0 */
4008 target->tap = tap;
4009 } else {
4010 if (goi->argc != 0) {
4011 goto no_params;
4014 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4015 /* loop for more e*/
4016 break;
4017 case TCFG_DBGBASE:
4018 if (goi->isconfigure) {
4019 e = Jim_GetOpt_Wide(goi, &w);
4020 if (e != JIM_OK) {
4021 return e;
4023 target->dbgbase = (uint32_t)w;
4024 target->dbgbase_set = true;
4025 } else {
4026 if (goi->argc != 0) {
4027 goto no_params;
4030 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4031 /* loop for more */
4032 break;
4034 case TCFG_RTOS:
4035 /* RTOS */
4037 int result = rtos_create( goi, target );
4038 if ( result != JIM_OK )
4040 return result;
4043 /* loop for more */
4044 break;
4046 } /* while (goi->argc) */
4049 /* done - we return */
4050 return JIM_OK;
4053 static int
4054 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4056 Jim_GetOptInfo goi;
4058 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4059 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4060 int need_args = 1 + goi.isconfigure;
4061 if (goi.argc < need_args)
4063 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4064 goi.isconfigure
4065 ? "missing: -option VALUE ..."
4066 : "missing: -option ...");
4067 return JIM_ERR;
4069 struct target *target = Jim_CmdPrivData(goi.interp);
4070 return target_configure(&goi, target);
4073 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4075 const char *cmd_name = Jim_GetString(argv[0], NULL);
4077 Jim_GetOptInfo goi;
4078 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4080 if (goi.argc < 2 || goi.argc > 4)
4082 Jim_SetResultFormatted(goi.interp,
4083 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4084 return JIM_ERR;
4087 target_write_fn fn;
4088 fn = target_write_memory_fast;
4090 int e;
4091 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4093 /* consume it */
4094 struct Jim_Obj *obj;
4095 e = Jim_GetOpt_Obj(&goi, &obj);
4096 if (e != JIM_OK)
4097 return e;
4099 fn = target_write_phys_memory;
4102 jim_wide a;
4103 e = Jim_GetOpt_Wide(&goi, &a);
4104 if (e != JIM_OK)
4105 return e;
4107 jim_wide b;
4108 e = Jim_GetOpt_Wide(&goi, &b);
4109 if (e != JIM_OK)
4110 return e;
4112 jim_wide c = 1;
4113 if (goi.argc == 1)
4115 e = Jim_GetOpt_Wide(&goi, &c);
4116 if (e != JIM_OK)
4117 return e;
4120 /* all args must be consumed */
4121 if (goi.argc != 0)
4123 return JIM_ERR;
4126 struct target *target = Jim_CmdPrivData(goi.interp);
4127 unsigned data_size;
4128 if (strcasecmp(cmd_name, "mww") == 0) {
4129 data_size = 4;
4131 else if (strcasecmp(cmd_name, "mwh") == 0) {
4132 data_size = 2;
4134 else if (strcasecmp(cmd_name, "mwb") == 0) {
4135 data_size = 1;
4136 } else {
4137 LOG_ERROR("command '%s' unknown: ", cmd_name);
4138 return JIM_ERR;
4141 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4144 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4146 const char *cmd_name = Jim_GetString(argv[0], NULL);
4148 Jim_GetOptInfo goi;
4149 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4151 if ((goi.argc < 1) || (goi.argc > 3))
4153 Jim_SetResultFormatted(goi.interp,
4154 "usage: %s [phys] <address> [<count>]", cmd_name);
4155 return JIM_ERR;
4158 int (*fn)(struct target *target,
4159 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4160 fn=target_read_memory;
4162 int e;
4163 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4165 /* consume it */
4166 struct Jim_Obj *obj;
4167 e = Jim_GetOpt_Obj(&goi, &obj);
4168 if (e != JIM_OK)
4169 return e;
4171 fn=target_read_phys_memory;
4174 jim_wide a;
4175 e = Jim_GetOpt_Wide(&goi, &a);
4176 if (e != JIM_OK) {
4177 return JIM_ERR;
4179 jim_wide c;
4180 if (goi.argc == 1) {
4181 e = Jim_GetOpt_Wide(&goi, &c);
4182 if (e != JIM_OK) {
4183 return JIM_ERR;
4185 } else {
4186 c = 1;
4189 /* all args must be consumed */
4190 if (goi.argc != 0)
4192 return JIM_ERR;
4195 jim_wide b = 1; /* shut up gcc */
4196 if (strcasecmp(cmd_name, "mdw") == 0)
4197 b = 4;
4198 else if (strcasecmp(cmd_name, "mdh") == 0)
4199 b = 2;
4200 else if (strcasecmp(cmd_name, "mdb") == 0)
4201 b = 1;
4202 else {
4203 LOG_ERROR("command '%s' unknown: ", cmd_name);
4204 return JIM_ERR;
4207 /* convert count to "bytes" */
4208 c = c * b;
4210 struct target *target = Jim_CmdPrivData(goi.interp);
4211 uint8_t target_buf[32];
4212 jim_wide x, y, z;
4213 while (c > 0) {
4214 y = c;
4215 if (y > 16) {
4216 y = 16;
4218 e = fn(target, a, b, y / b, target_buf);
4219 if (e != ERROR_OK) {
4220 char tmp[10];
4221 snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4222 Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4223 return JIM_ERR;
4226 command_print(NULL, "0x%08x ", (int)(a));
4227 switch (b) {
4228 case 4:
4229 for (x = 0; x < 16 && x < y; x += 4)
4231 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4232 command_print(NULL, "%08x ", (int)(z));
4234 for (; (x < 16) ; x += 4) {
4235 command_print(NULL, " ");
4237 break;
4238 case 2:
4239 for (x = 0; x < 16 && x < y; x += 2)
4241 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4242 command_print(NULL, "%04x ", (int)(z));
4244 for (; (x < 16) ; x += 2) {
4245 command_print(NULL, " ");
4247 break;
4248 case 1:
4249 default:
4250 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4251 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4252 command_print(NULL, "%02x ", (int)(z));
4254 for (; (x < 16) ; x += 1) {
4255 command_print(NULL, " ");
4257 break;
4259 /* ascii-ify the bytes */
4260 for (x = 0 ; x < y ; x++) {
4261 if ((target_buf[x] >= 0x20) &&
4262 (target_buf[x] <= 0x7e)) {
4263 /* good */
4264 } else {
4265 /* smack it */
4266 target_buf[x] = '.';
4269 /* space pad */
4270 while (x < 16) {
4271 target_buf[x] = ' ';
4272 x++;
4274 /* terminate */
4275 target_buf[16] = 0;
4276 /* print - with a newline */
4277 command_print(NULL, "%s\n", target_buf);
4278 /* NEXT... */
4279 c -= 16;
4280 a += 16;
4282 return JIM_OK;
4285 static int jim_target_mem2array(Jim_Interp *interp,
4286 int argc, Jim_Obj *const *argv)
4288 struct target *target = Jim_CmdPrivData(interp);
4289 return target_mem2array(interp, target, argc - 1, argv + 1);
4292 static int jim_target_array2mem(Jim_Interp *interp,
4293 int argc, Jim_Obj *const *argv)
4295 struct target *target = Jim_CmdPrivData(interp);
4296 return target_array2mem(interp, target, argc - 1, argv + 1);
4299 static int jim_target_tap_disabled(Jim_Interp *interp)
4301 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4302 return JIM_ERR;
4305 static int jim_target_examine(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 = target->type->examine(target);
4317 if (e != ERROR_OK)
4319 return JIM_ERR;
4321 return JIM_OK;
4324 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4326 if (argc != 1)
4328 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4329 return JIM_ERR;
4331 struct target *target = Jim_CmdPrivData(interp);
4333 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4334 return JIM_ERR;
4336 return JIM_OK;
4339 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4341 if (argc != 1)
4343 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4344 return JIM_ERR;
4346 struct target *target = Jim_CmdPrivData(interp);
4347 if (!target->tap->enabled)
4348 return jim_target_tap_disabled(interp);
4350 int e;
4351 if (!(target_was_examined(target))) {
4352 e = ERROR_TARGET_NOT_EXAMINED;
4353 } else {
4354 e = target->type->poll(target);
4356 if (e != ERROR_OK)
4358 return JIM_ERR;
4360 return JIM_OK;
4363 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4365 Jim_GetOptInfo goi;
4366 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4368 if (goi.argc != 2)
4370 Jim_WrongNumArgs(interp, 0, argv,
4371 "([tT]|[fF]|assert|deassert) BOOL");
4372 return JIM_ERR;
4375 Jim_Nvp *n;
4376 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4377 if (e != JIM_OK)
4379 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4380 return e;
4382 /* the halt or not param */
4383 jim_wide a;
4384 e = Jim_GetOpt_Wide(&goi, &a);
4385 if (e != JIM_OK)
4386 return e;
4388 struct target *target = Jim_CmdPrivData(goi.interp);
4389 if (!target->tap->enabled)
4390 return jim_target_tap_disabled(interp);
4391 if (!(target_was_examined(target)))
4393 LOG_ERROR("Target not examined yet");
4394 return ERROR_TARGET_NOT_EXAMINED;
4396 if (!target->type->assert_reset || !target->type->deassert_reset)
4398 Jim_SetResultFormatted(interp,
4399 "No target-specific reset for %s",
4400 target_name(target));
4401 return JIM_ERR;
4403 /* determine if we should halt or not. */
4404 target->reset_halt = !!a;
4405 /* When this happens - all workareas are invalid. */
4406 target_free_all_working_areas_restore(target, 0);
4408 /* do the assert */
4409 if (n->value == NVP_ASSERT) {
4410 e = target->type->assert_reset(target);
4411 } else {
4412 e = target->type->deassert_reset(target);
4414 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4417 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4419 if (argc != 1) {
4420 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4421 return JIM_ERR;
4423 struct target *target = Jim_CmdPrivData(interp);
4424 if (!target->tap->enabled)
4425 return jim_target_tap_disabled(interp);
4426 int e = target->type->halt(target);
4427 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4430 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4432 Jim_GetOptInfo goi;
4433 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4435 /* params: <name> statename timeoutmsecs */
4436 if (goi.argc != 2)
4438 const char *cmd_name = Jim_GetString(argv[0], NULL);
4439 Jim_SetResultFormatted(goi.interp,
4440 "%s <state_name> <timeout_in_msec>", cmd_name);
4441 return JIM_ERR;
4444 Jim_Nvp *n;
4445 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4446 if (e != JIM_OK) {
4447 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4448 return e;
4450 jim_wide a;
4451 e = Jim_GetOpt_Wide(&goi, &a);
4452 if (e != JIM_OK) {
4453 return e;
4455 struct target *target = Jim_CmdPrivData(interp);
4456 if (!target->tap->enabled)
4457 return jim_target_tap_disabled(interp);
4459 e = target_wait_state(target, n->value, a);
4460 if (e != ERROR_OK)
4462 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4463 Jim_SetResultFormatted(goi.interp,
4464 "target: %s wait %s fails (%#s) %s",
4465 target_name(target), n->name,
4466 eObj, target_strerror_safe(e));
4467 Jim_FreeNewObj(interp, eObj);
4468 return JIM_ERR;
4470 return JIM_OK;
4472 /* List for human, Events defined for this target.
4473 * scripts/programs should use 'name cget -event NAME'
4475 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4477 struct command_context *cmd_ctx = current_command_context(interp);
4478 assert (cmd_ctx != NULL);
4480 struct target *target = Jim_CmdPrivData(interp);
4481 struct target_event_action *teap = target->event_action;
4482 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4483 target->target_number,
4484 target_name(target));
4485 command_print(cmd_ctx, "%-25s | Body", "Event");
4486 command_print(cmd_ctx, "------------------------- | "
4487 "----------------------------------------");
4488 while (teap)
4490 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4491 command_print(cmd_ctx, "%-25s | %s",
4492 opt->name, Jim_GetString(teap->body, NULL));
4493 teap = teap->next;
4495 command_print(cmd_ctx, "***END***");
4496 return JIM_OK;
4498 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4500 if (argc != 1)
4502 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4503 return JIM_ERR;
4505 struct target *target = Jim_CmdPrivData(interp);
4506 Jim_SetResultString(interp, target_state_name(target), -1);
4507 return JIM_OK;
4509 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4511 Jim_GetOptInfo goi;
4512 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4513 if (goi.argc != 1)
4515 const char *cmd_name = Jim_GetString(argv[0], NULL);
4516 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4517 return JIM_ERR;
4519 Jim_Nvp *n;
4520 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4521 if (e != JIM_OK)
4523 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4524 return e;
4526 struct target *target = Jim_CmdPrivData(interp);
4527 target_handle_event(target, n->value);
4528 return JIM_OK;
4531 static const struct command_registration target_instance_command_handlers[] = {
4533 .name = "configure",
4534 .mode = COMMAND_CONFIG,
4535 .jim_handler = jim_target_configure,
4536 .help = "configure a new target for use",
4537 .usage = "[target_attribute ...]",
4540 .name = "cget",
4541 .mode = COMMAND_ANY,
4542 .jim_handler = jim_target_configure,
4543 .help = "returns the specified target attribute",
4544 .usage = "target_attribute",
4547 .name = "mww",
4548 .mode = COMMAND_EXEC,
4549 .jim_handler = jim_target_mw,
4550 .help = "Write 32-bit word(s) to target memory",
4551 .usage = "address data [count]",
4554 .name = "mwh",
4555 .mode = COMMAND_EXEC,
4556 .jim_handler = jim_target_mw,
4557 .help = "Write 16-bit half-word(s) to target memory",
4558 .usage = "address data [count]",
4561 .name = "mwb",
4562 .mode = COMMAND_EXEC,
4563 .jim_handler = jim_target_mw,
4564 .help = "Write byte(s) to target memory",
4565 .usage = "address data [count]",
4568 .name = "mdw",
4569 .mode = COMMAND_EXEC,
4570 .jim_handler = jim_target_md,
4571 .help = "Display target memory as 32-bit words",
4572 .usage = "address [count]",
4575 .name = "mdh",
4576 .mode = COMMAND_EXEC,
4577 .jim_handler = jim_target_md,
4578 .help = "Display target memory as 16-bit half-words",
4579 .usage = "address [count]",
4582 .name = "mdb",
4583 .mode = COMMAND_EXEC,
4584 .jim_handler = jim_target_md,
4585 .help = "Display target memory as 8-bit bytes",
4586 .usage = "address [count]",
4589 .name = "array2mem",
4590 .mode = COMMAND_EXEC,
4591 .jim_handler = jim_target_array2mem,
4592 .help = "Writes Tcl array of 8/16/32 bit numbers "
4593 "to target memory",
4594 .usage = "arrayname bitwidth address count",
4597 .name = "mem2array",
4598 .mode = COMMAND_EXEC,
4599 .jim_handler = jim_target_mem2array,
4600 .help = "Loads Tcl array of 8/16/32 bit numbers "
4601 "from target memory",
4602 .usage = "arrayname bitwidth address count",
4605 .name = "eventlist",
4606 .mode = COMMAND_EXEC,
4607 .jim_handler = jim_target_event_list,
4608 .help = "displays a table of events defined for this target",
4611 .name = "curstate",
4612 .mode = COMMAND_EXEC,
4613 .jim_handler = jim_target_current_state,
4614 .help = "displays the current state of this target",
4617 .name = "arp_examine",
4618 .mode = COMMAND_EXEC,
4619 .jim_handler = jim_target_examine,
4620 .help = "used internally for reset processing",
4623 .name = "arp_halt_gdb",
4624 .mode = COMMAND_EXEC,
4625 .jim_handler = jim_target_halt_gdb,
4626 .help = "used internally for reset processing to halt GDB",
4629 .name = "arp_poll",
4630 .mode = COMMAND_EXEC,
4631 .jim_handler = jim_target_poll,
4632 .help = "used internally for reset processing",
4635 .name = "arp_reset",
4636 .mode = COMMAND_EXEC,
4637 .jim_handler = jim_target_reset,
4638 .help = "used internally for reset processing",
4641 .name = "arp_halt",
4642 .mode = COMMAND_EXEC,
4643 .jim_handler = jim_target_halt,
4644 .help = "used internally for reset processing",
4647 .name = "arp_waitstate",
4648 .mode = COMMAND_EXEC,
4649 .jim_handler = jim_target_wait_state,
4650 .help = "used internally for reset processing",
4653 .name = "invoke-event",
4654 .mode = COMMAND_EXEC,
4655 .jim_handler = jim_target_invoke_event,
4656 .help = "invoke handler for specified event",
4657 .usage = "event_name",
4659 COMMAND_REGISTRATION_DONE
4662 static int target_create(Jim_GetOptInfo *goi)
4664 Jim_Obj *new_cmd;
4665 Jim_Cmd *cmd;
4666 const char *cp;
4667 char *cp2;
4668 int e;
4669 int x;
4670 struct target *target;
4671 struct command_context *cmd_ctx;
4673 cmd_ctx = current_command_context(goi->interp);
4674 assert (cmd_ctx != NULL);
4676 if (goi->argc < 3) {
4677 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4678 return JIM_ERR;
4681 /* COMMAND */
4682 Jim_GetOpt_Obj(goi, &new_cmd);
4683 /* does this command exist? */
4684 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4685 if (cmd) {
4686 cp = Jim_GetString(new_cmd, NULL);
4687 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4688 return JIM_ERR;
4691 /* TYPE */
4692 e = Jim_GetOpt_String(goi, &cp2, NULL);
4693 cp = cp2;
4694 /* now does target type exist */
4695 for (x = 0 ; target_types[x] ; x++) {
4696 if (0 == strcmp(cp, target_types[x]->name)) {
4697 /* found */
4698 break;
4701 if (target_types[x] == NULL) {
4702 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4703 for (x = 0 ; target_types[x] ; x++) {
4704 if (target_types[x + 1]) {
4705 Jim_AppendStrings(goi->interp,
4706 Jim_GetResult(goi->interp),
4707 target_types[x]->name,
4708 ", ", NULL);
4709 } else {
4710 Jim_AppendStrings(goi->interp,
4711 Jim_GetResult(goi->interp),
4712 " or ",
4713 target_types[x]->name,NULL);
4716 return JIM_ERR;
4719 /* Create it */
4720 target = calloc(1,sizeof(struct target));
4721 /* set target number */
4722 target->target_number = new_target_number();
4724 /* allocate memory for each unique target type */
4725 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4727 memcpy(target->type, target_types[x], sizeof(struct target_type));
4729 /* will be set by "-endian" */
4730 target->endianness = TARGET_ENDIAN_UNKNOWN;
4732 /* default to first core, override with -coreid */
4733 target->coreid = 0;
4735 target->working_area = 0x0;
4736 target->working_area_size = 0x0;
4737 target->working_areas = NULL;
4738 target->backup_working_area = 0;
4740 target->state = TARGET_UNKNOWN;
4741 target->debug_reason = DBG_REASON_UNDEFINED;
4742 target->reg_cache = NULL;
4743 target->breakpoints = NULL;
4744 target->watchpoints = NULL;
4745 target->next = NULL;
4746 target->arch_info = NULL;
4748 target->display = 1;
4750 target->halt_issued = false;
4752 /* initialize trace information */
4753 target->trace_info = malloc(sizeof(struct trace));
4754 target->trace_info->num_trace_points = 0;
4755 target->trace_info->trace_points_size = 0;
4756 target->trace_info->trace_points = NULL;
4757 target->trace_info->trace_history_size = 0;
4758 target->trace_info->trace_history = NULL;
4759 target->trace_info->trace_history_pos = 0;
4760 target->trace_info->trace_history_overflowed = 0;
4762 target->dbgmsg = NULL;
4763 target->dbg_msg_enabled = 0;
4765 target->endianness = TARGET_ENDIAN_UNKNOWN;
4767 target->rtos = NULL;
4768 target->rtos_auto_detect = false;
4770 /* Do the rest as "configure" options */
4771 goi->isconfigure = 1;
4772 e = target_configure(goi, target);
4774 if (target->tap == NULL)
4776 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4777 e = JIM_ERR;
4780 if (e != JIM_OK) {
4781 free(target->type);
4782 free(target);
4783 return e;
4786 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4787 /* default endian to little if not specified */
4788 target->endianness = TARGET_LITTLE_ENDIAN;
4791 /* incase variant is not set */
4792 if (!target->variant)
4793 target->variant = strdup("");
4795 cp = Jim_GetString(new_cmd, NULL);
4796 target->cmd_name = strdup(cp);
4798 /* create the target specific commands */
4799 if (target->type->commands) {
4800 e = register_commands(cmd_ctx, NULL, target->type->commands);
4801 if (ERROR_OK != e)
4802 LOG_ERROR("unable to register '%s' commands", cp);
4804 if (target->type->target_create) {
4805 (*(target->type->target_create))(target, goi->interp);
4808 /* append to end of list */
4810 struct target **tpp;
4811 tpp = &(all_targets);
4812 while (*tpp) {
4813 tpp = &((*tpp)->next);
4815 *tpp = target;
4818 /* now - create the new target name command */
4819 const const struct command_registration target_subcommands[] = {
4821 .chain = target_instance_command_handlers,
4824 .chain = target->type->commands,
4826 COMMAND_REGISTRATION_DONE
4828 const const struct command_registration target_commands[] = {
4830 .name = cp,
4831 .mode = COMMAND_ANY,
4832 .help = "target command group",
4833 .chain = target_subcommands,
4835 COMMAND_REGISTRATION_DONE
4837 e = register_commands(cmd_ctx, NULL, target_commands);
4838 if (ERROR_OK != e)
4839 return JIM_ERR;
4841 struct command *c = command_find_in_context(cmd_ctx, cp);
4842 assert(c);
4843 command_set_handler_data(c, target);
4845 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4848 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4850 if (argc != 1)
4852 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4853 return JIM_ERR;
4855 struct command_context *cmd_ctx = current_command_context(interp);
4856 assert (cmd_ctx != NULL);
4858 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4859 return JIM_OK;
4862 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4864 if (argc != 1)
4866 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4867 return JIM_ERR;
4869 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4870 for (unsigned x = 0; NULL != target_types[x]; x++)
4872 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4873 Jim_NewStringObj(interp, target_types[x]->name, -1));
4875 return JIM_OK;
4878 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4880 if (argc != 1)
4882 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4883 return JIM_ERR;
4885 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4886 struct target *target = all_targets;
4887 while (target)
4889 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4890 Jim_NewStringObj(interp, target_name(target), -1));
4891 target = target->next;
4893 return JIM_OK;
4896 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4898 Jim_GetOptInfo goi;
4899 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4900 if (goi.argc < 3)
4902 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4903 "<name> <target_type> [<target_options> ...]");
4904 return JIM_ERR;
4906 return target_create(&goi);
4909 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4911 Jim_GetOptInfo goi;
4912 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4914 /* It's OK to remove this mechanism sometime after August 2010 or so */
4915 LOG_WARNING("don't use numbers as target identifiers; use names");
4916 if (goi.argc != 1)
4918 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
4919 return JIM_ERR;
4921 jim_wide w;
4922 int e = Jim_GetOpt_Wide(&goi, &w);
4923 if (e != JIM_OK)
4924 return JIM_ERR;
4926 struct target *target;
4927 for (target = all_targets; NULL != target; target = target->next)
4929 if (target->target_number != w)
4930 continue;
4932 Jim_SetResultString(goi.interp, target_name(target), -1);
4933 return JIM_OK;
4936 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
4937 Jim_SetResultFormatted(goi.interp,
4938 "Target: number %#s does not exist", wObj);
4939 Jim_FreeNewObj(interp, wObj);
4941 return JIM_ERR;
4944 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4946 if (argc != 1)
4948 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4949 return JIM_ERR;
4951 unsigned count = 0;
4952 struct target *target = all_targets;
4953 while (NULL != target)
4955 target = target->next;
4956 count++;
4958 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4959 return JIM_OK;
4962 static const struct command_registration target_subcommand_handlers[] = {
4964 .name = "init",
4965 .mode = COMMAND_CONFIG,
4966 .handler = handle_target_init_command,
4967 .help = "initialize targets",
4970 .name = "create",
4971 /* REVISIT this should be COMMAND_CONFIG ... */
4972 .mode = COMMAND_ANY,
4973 .jim_handler = jim_target_create,
4974 .usage = "name type '-chain-position' name [options ...]",
4975 .help = "Creates and selects a new target",
4978 .name = "current",
4979 .mode = COMMAND_ANY,
4980 .jim_handler = jim_target_current,
4981 .help = "Returns the currently selected target",
4984 .name = "types",
4985 .mode = COMMAND_ANY,
4986 .jim_handler = jim_target_types,
4987 .help = "Returns the available target types as "
4988 "a list of strings",
4991 .name = "names",
4992 .mode = COMMAND_ANY,
4993 .jim_handler = jim_target_names,
4994 .help = "Returns the names of all targets as a list of strings",
4997 .name = "number",
4998 .mode = COMMAND_ANY,
4999 .jim_handler = jim_target_number,
5000 .usage = "number",
5001 .help = "Returns the name of the numbered target "
5002 "(DEPRECATED)",
5005 .name = "count",
5006 .mode = COMMAND_ANY,
5007 .jim_handler = jim_target_count,
5008 .help = "Returns the number of targets as an integer "
5009 "(DEPRECATED)",
5011 COMMAND_REGISTRATION_DONE
5014 struct FastLoad
5016 uint32_t address;
5017 uint8_t *data;
5018 int length;
5022 static int fastload_num;
5023 static struct FastLoad *fastload;
5025 static void free_fastload(void)
5027 if (fastload != NULL)
5029 int i;
5030 for (i = 0; i < fastload_num; i++)
5032 if (fastload[i].data)
5033 free(fastload[i].data);
5035 free(fastload);
5036 fastload = NULL;
5043 COMMAND_HANDLER(handle_fast_load_image_command)
5045 uint8_t *buffer;
5046 size_t buf_cnt;
5047 uint32_t image_size;
5048 uint32_t min_address = 0;
5049 uint32_t max_address = 0xffffffff;
5050 int i;
5052 struct image image;
5054 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5055 &image, &min_address, &max_address);
5056 if (ERROR_OK != retval)
5057 return retval;
5059 struct duration bench;
5060 duration_start(&bench);
5062 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5063 if (retval != ERROR_OK)
5065 return retval;
5068 image_size = 0x0;
5069 retval = ERROR_OK;
5070 fastload_num = image.num_sections;
5071 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5072 if (fastload == NULL)
5074 command_print(CMD_CTX, "out of memory");
5075 image_close(&image);
5076 return ERROR_FAIL;
5078 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5079 for (i = 0; i < image.num_sections; i++)
5081 buffer = malloc(image.sections[i].size);
5082 if (buffer == NULL)
5084 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5085 (int)(image.sections[i].size));
5086 retval = ERROR_FAIL;
5087 break;
5090 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
5092 free(buffer);
5093 break;
5096 uint32_t offset = 0;
5097 uint32_t length = buf_cnt;
5100 /* DANGER!!! beware of unsigned comparision here!!! */
5102 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
5103 (image.sections[i].base_address < max_address))
5105 if (image.sections[i].base_address < min_address)
5107 /* clip addresses below */
5108 offset += min_address-image.sections[i].base_address;
5109 length -= offset;
5112 if (image.sections[i].base_address + buf_cnt > max_address)
5114 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5117 fastload[i].address = image.sections[i].base_address + offset;
5118 fastload[i].data = malloc(length);
5119 if (fastload[i].data == NULL)
5121 free(buffer);
5122 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5123 length);
5124 retval = ERROR_FAIL;
5125 break;
5127 memcpy(fastload[i].data, buffer + offset, length);
5128 fastload[i].length = length;
5130 image_size += length;
5131 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5132 (unsigned int)length,
5133 ((unsigned int)(image.sections[i].base_address + offset)));
5136 free(buffer);
5139 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5141 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5142 "in %fs (%0.3f KiB/s)", image_size,
5143 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5145 command_print(CMD_CTX,
5146 "WARNING: image has not been loaded to target!"
5147 "You can issue a 'fast_load' to finish loading.");
5150 image_close(&image);
5152 if (retval != ERROR_OK)
5154 free_fastload();
5157 return retval;
5160 COMMAND_HANDLER(handle_fast_load_command)
5162 if (CMD_ARGC > 0)
5163 return ERROR_COMMAND_SYNTAX_ERROR;
5164 if (fastload == NULL)
5166 LOG_ERROR("No image in memory");
5167 return ERROR_FAIL;
5169 int i;
5170 int ms = timeval_ms();
5171 int size = 0;
5172 int retval = ERROR_OK;
5173 for (i = 0; i < fastload_num;i++)
5175 struct target *target = get_current_target(CMD_CTX);
5176 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5177 (unsigned int)(fastload[i].address),
5178 (unsigned int)(fastload[i].length));
5179 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5180 if (retval != ERROR_OK)
5182 break;
5184 size += fastload[i].length;
5186 if (retval == ERROR_OK)
5188 int after = timeval_ms();
5189 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5191 return retval;
5194 static const struct command_registration target_command_handlers[] = {
5196 .name = "targets",
5197 .handler = handle_targets_command,
5198 .mode = COMMAND_ANY,
5199 .help = "change current default target (one parameter) "
5200 "or prints table of all targets (no parameters)",
5201 .usage = "[target]",
5204 .name = "target",
5205 .mode = COMMAND_CONFIG,
5206 .help = "configure target",
5208 .chain = target_subcommand_handlers,
5210 COMMAND_REGISTRATION_DONE
5213 int target_register_commands(struct command_context *cmd_ctx)
5215 return register_commands(cmd_ctx, NULL, target_command_handlers);
5218 static bool target_reset_nag = true;
5220 bool get_target_reset_nag(void)
5222 return target_reset_nag;
5225 COMMAND_HANDLER(handle_target_reset_nag)
5227 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5228 &target_reset_nag, "Nag after each reset about options to improve "
5229 "performance");
5232 static const struct command_registration target_exec_command_handlers[] = {
5234 .name = "fast_load_image",
5235 .handler = handle_fast_load_image_command,
5236 .mode = COMMAND_ANY,
5237 .help = "Load image into server memory for later use by "
5238 "fast_load; primarily for profiling",
5239 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5240 "[min_address [max_length]]",
5243 .name = "fast_load",
5244 .handler = handle_fast_load_command,
5245 .mode = COMMAND_EXEC,
5246 .help = "loads active fast load image to current target "
5247 "- mainly for profiling purposes",
5250 .name = "profile",
5251 .handler = handle_profile_command,
5252 .mode = COMMAND_EXEC,
5253 .help = "profiling samples the CPU PC",
5255 /** @todo don't register virt2phys() unless target supports it */
5257 .name = "virt2phys",
5258 .handler = handle_virt2phys_command,
5259 .mode = COMMAND_ANY,
5260 .help = "translate a virtual address into a physical address",
5261 .usage = "virtual_address",
5264 .name = "reg",
5265 .handler = handle_reg_command,
5266 .mode = COMMAND_EXEC,
5267 .help = "display or set a register; with no arguments, "
5268 "displays all registers and their values",
5269 .usage = "[(register_name|register_number) [value]]",
5272 .name = "poll",
5273 .handler = handle_poll_command,
5274 .mode = COMMAND_EXEC,
5275 .help = "poll target state; or reconfigure background polling",
5276 .usage = "['on'|'off']",
5279 .name = "wait_halt",
5280 .handler = handle_wait_halt_command,
5281 .mode = COMMAND_EXEC,
5282 .help = "wait up to the specified number of milliseconds "
5283 "(default 5) for a previously requested halt",
5284 .usage = "[milliseconds]",
5287 .name = "halt",
5288 .handler = handle_halt_command,
5289 .mode = COMMAND_EXEC,
5290 .help = "request target to halt, then wait up to the specified"
5291 "number of milliseconds (default 5) for it to complete",
5292 .usage = "[milliseconds]",
5295 .name = "resume",
5296 .handler = handle_resume_command,
5297 .mode = COMMAND_EXEC,
5298 .help = "resume target execution from current PC or address",
5299 .usage = "[address]",
5302 .name = "reset",
5303 .handler = handle_reset_command,
5304 .mode = COMMAND_EXEC,
5305 .usage = "[run|halt|init]",
5306 .help = "Reset all targets into the specified mode."
5307 "Default reset mode is run, if not given.",
5310 .name = "soft_reset_halt",
5311 .handler = handle_soft_reset_halt_command,
5312 .mode = COMMAND_EXEC,
5313 .help = "halt the target and do a soft reset",
5316 .name = "step",
5317 .handler = handle_step_command,
5318 .mode = COMMAND_EXEC,
5319 .help = "step one instruction from current PC or address",
5320 .usage = "[address]",
5323 .name = "mdw",
5324 .handler = handle_md_command,
5325 .mode = COMMAND_EXEC,
5326 .help = "display memory words",
5327 .usage = "['phys'] address [count]",
5330 .name = "mdh",
5331 .handler = handle_md_command,
5332 .mode = COMMAND_EXEC,
5333 .help = "display memory half-words",
5334 .usage = "['phys'] address [count]",
5337 .name = "mdb",
5338 .handler = handle_md_command,
5339 .mode = COMMAND_EXEC,
5340 .help = "display memory bytes",
5341 .usage = "['phys'] address [count]",
5344 .name = "mww",
5345 .handler = handle_mw_command,
5346 .mode = COMMAND_EXEC,
5347 .help = "write memory word",
5348 .usage = "['phys'] address value [count]",
5351 .name = "mwh",
5352 .handler = handle_mw_command,
5353 .mode = COMMAND_EXEC,
5354 .help = "write memory half-word",
5355 .usage = "['phys'] address value [count]",
5358 .name = "mwb",
5359 .handler = handle_mw_command,
5360 .mode = COMMAND_EXEC,
5361 .help = "write memory byte",
5362 .usage = "['phys'] address value [count]",
5365 .name = "bp",
5366 .handler = handle_bp_command,
5367 .mode = COMMAND_EXEC,
5368 .help = "list or set hardware or software breakpoint",
5369 .usage = "[address length ['hw']]",
5372 .name = "rbp",
5373 .handler = handle_rbp_command,
5374 .mode = COMMAND_EXEC,
5375 .help = "remove breakpoint",
5376 .usage = "address",
5379 .name = "wp",
5380 .handler = handle_wp_command,
5381 .mode = COMMAND_EXEC,
5382 .help = "list (no params) or create watchpoints",
5383 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5386 .name = "rwp",
5387 .handler = handle_rwp_command,
5388 .mode = COMMAND_EXEC,
5389 .help = "remove watchpoint",
5390 .usage = "address",
5393 .name = "load_image",
5394 .handler = handle_load_image_command,
5395 .mode = COMMAND_EXEC,
5396 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5397 "[min_address] [max_length]",
5400 .name = "dump_image",
5401 .handler = handle_dump_image_command,
5402 .mode = COMMAND_EXEC,
5403 .usage = "filename address size",
5406 .name = "verify_image",
5407 .handler = handle_verify_image_command,
5408 .mode = COMMAND_EXEC,
5409 .usage = "filename [offset [type]]",
5412 .name = "test_image",
5413 .handler = handle_test_image_command,
5414 .mode = COMMAND_EXEC,
5415 .usage = "filename [offset [type]]",
5418 .name = "mem2array",
5419 .mode = COMMAND_EXEC,
5420 .jim_handler = jim_mem2array,
5421 .help = "read 8/16/32 bit memory and return as a TCL array "
5422 "for script processing",
5423 .usage = "arrayname bitwidth address count",
5426 .name = "array2mem",
5427 .mode = COMMAND_EXEC,
5428 .jim_handler = jim_array2mem,
5429 .help = "convert a TCL array to memory locations "
5430 "and write the 8/16/32 bit values",
5431 .usage = "arrayname bitwidth address count",
5434 .name = "reset_nag",
5435 .handler = handle_target_reset_nag,
5436 .mode = COMMAND_ANY,
5437 .help = "Nag after each reset about options that could have been "
5438 "enabled to improve performance. ",
5439 .usage = "['enable'|'disable']",
5441 COMMAND_REGISTRATION_DONE
5443 static int target_register_user_commands(struct command_context *cmd_ctx)
5445 int retval = ERROR_OK;
5446 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5447 return retval;
5449 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5450 return retval;
5453 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);