smp : infra for smp minimum support
[openocd.git] / src / target / target.c
bloba2e3ccfb06bf03d52f50fac497eb6f79d27f2e99
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 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
22 * *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
27 * *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
32 * *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the *
35 * Free Software Foundation, Inc., *
36 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
37 ***************************************************************************/
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
42 #include <helper/time_support.h>
43 #include <jtag/jtag.h>
44 #include <flash/nor/core.h>
46 #include "target.h"
47 #include "target_type.h"
48 #include "target_request.h"
49 #include "breakpoints.h"
50 #include "register.h"
51 #include "trace.h"
52 #include "image.h"
53 #include "rtos/rtos.h"
56 static int target_read_buffer_default(struct target *target, uint32_t address,
57 uint32_t size, uint8_t *buffer);
58 static int target_write_buffer_default(struct target *target, uint32_t address,
59 uint32_t size, const uint8_t *buffer);
60 static int target_array2mem(Jim_Interp *interp, struct target *target,
61 int argc, Jim_Obj *const *argv);
62 static int target_mem2array(Jim_Interp *interp, struct target *target,
63 int argc, Jim_Obj *const *argv);
64 static int target_register_user_commands(struct command_context *cmd_ctx);
66 /* targets */
67 extern struct target_type arm7tdmi_target;
68 extern struct target_type arm720t_target;
69 extern struct target_type arm9tdmi_target;
70 extern struct target_type arm920t_target;
71 extern struct target_type arm966e_target;
72 extern struct target_type arm946e_target;
73 extern struct target_type arm926ejs_target;
74 extern struct target_type fa526_target;
75 extern struct target_type feroceon_target;
76 extern struct target_type dragonite_target;
77 extern struct target_type xscale_target;
78 extern struct target_type cortexm3_target;
79 extern struct target_type cortexa8_target;
80 extern struct target_type arm11_target;
81 extern struct target_type mips_m4k_target;
82 extern struct target_type avr_target;
83 extern struct target_type dsp563xx_target;
84 extern struct target_type testee_target;
85 extern struct target_type avr32_ap7k_target;
87 static struct target_type *target_types[] =
89 &arm7tdmi_target,
90 &arm9tdmi_target,
91 &arm920t_target,
92 &arm720t_target,
93 &arm966e_target,
94 &arm946e_target,
95 &arm926ejs_target,
96 &fa526_target,
97 &feroceon_target,
98 &dragonite_target,
99 &xscale_target,
100 &cortexm3_target,
101 &cortexa8_target,
102 &arm11_target,
103 &mips_m4k_target,
104 &avr_target,
105 &dsp563xx_target,
106 &testee_target,
107 &avr32_ap7k_target,
108 NULL,
111 struct target *all_targets = NULL;
112 static struct target_event_callback *target_event_callbacks = NULL;
113 static struct target_timer_callback *target_timer_callbacks = NULL;
114 static const int polling_interval = 100;
116 static const Jim_Nvp nvp_assert[] = {
117 { .name = "assert", NVP_ASSERT },
118 { .name = "deassert", NVP_DEASSERT },
119 { .name = "T", NVP_ASSERT },
120 { .name = "F", NVP_DEASSERT },
121 { .name = "t", NVP_ASSERT },
122 { .name = "f", NVP_DEASSERT },
123 { .name = NULL, .value = -1 }
126 static const Jim_Nvp nvp_error_target[] = {
127 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
128 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
129 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
130 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
131 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
132 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
133 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
134 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
135 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
136 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
137 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
138 { .value = -1, .name = NULL }
141 static const char *target_strerror_safe(int err)
143 const Jim_Nvp *n;
145 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
146 if (n->name == NULL) {
147 return "unknown";
148 } else {
149 return n->name;
153 static const Jim_Nvp nvp_target_event[] = {
154 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
155 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
157 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
158 { .value = TARGET_EVENT_HALTED, .name = "halted" },
159 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
160 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
161 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
163 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
164 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
166 /* historical name */
168 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
170 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
171 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
172 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
173 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
174 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
175 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
176 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
177 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
178 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
179 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
180 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
182 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
183 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
185 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
186 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
188 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
189 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
191 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
192 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
194 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
195 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
197 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
198 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
199 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
201 { .name = NULL, .value = -1 }
204 static const Jim_Nvp nvp_target_state[] = {
205 { .name = "unknown", .value = TARGET_UNKNOWN },
206 { .name = "running", .value = TARGET_RUNNING },
207 { .name = "halted", .value = TARGET_HALTED },
208 { .name = "reset", .value = TARGET_RESET },
209 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
210 { .name = NULL, .value = -1 },
213 static const Jim_Nvp nvp_target_debug_reason [] = {
214 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
215 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
216 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
217 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
218 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
219 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
220 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
221 { .name = NULL, .value = -1 },
224 static const Jim_Nvp nvp_target_endian[] = {
225 { .name = "big", .value = TARGET_BIG_ENDIAN },
226 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
227 { .name = "be", .value = TARGET_BIG_ENDIAN },
228 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
229 { .name = NULL, .value = -1 },
232 static const Jim_Nvp nvp_reset_modes[] = {
233 { .name = "unknown", .value = RESET_UNKNOWN },
234 { .name = "run" , .value = RESET_RUN },
235 { .name = "halt" , .value = RESET_HALT },
236 { .name = "init" , .value = RESET_INIT },
237 { .name = NULL , .value = -1 },
240 const char *debug_reason_name(struct target *t)
242 const char *cp;
244 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
245 t->debug_reason)->name;
246 if (!cp) {
247 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
248 cp = "(*BUG*unknown*BUG*)";
250 return cp;
253 const char *
254 target_state_name( struct target *t )
256 const char *cp;
257 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
258 if( !cp ){
259 LOG_ERROR("Invalid target state: %d", (int)(t->state));
260 cp = "(*BUG*unknown*BUG*)";
262 return cp;
265 /* determine the number of the new target */
266 static int new_target_number(void)
268 struct target *t;
269 int x;
271 /* number is 0 based */
272 x = -1;
273 t = all_targets;
274 while (t) {
275 if (x < t->target_number) {
276 x = t->target_number;
278 t = t->next;
280 return x + 1;
283 /* read a uint32_t from a buffer in target memory endianness */
284 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
286 if (target->endianness == TARGET_LITTLE_ENDIAN)
287 return le_to_h_u32(buffer);
288 else
289 return be_to_h_u32(buffer);
292 /* read a uint24_t from a buffer in target memory endianness */
293 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
295 if (target->endianness == TARGET_LITTLE_ENDIAN)
296 return le_to_h_u24(buffer);
297 else
298 return be_to_h_u24(buffer);
301 /* read a uint16_t from a buffer in target memory endianness */
302 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
304 if (target->endianness == TARGET_LITTLE_ENDIAN)
305 return le_to_h_u16(buffer);
306 else
307 return be_to_h_u16(buffer);
310 /* read a uint8_t from a buffer in target memory endianness */
311 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
313 return *buffer & 0x0ff;
316 /* write a uint32_t to a buffer in target memory endianness */
317 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
319 if (target->endianness == TARGET_LITTLE_ENDIAN)
320 h_u32_to_le(buffer, value);
321 else
322 h_u32_to_be(buffer, value);
325 /* write a uint24_t to a buffer in target memory endianness */
326 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
328 if (target->endianness == TARGET_LITTLE_ENDIAN)
329 h_u24_to_le(buffer, value);
330 else
331 h_u24_to_be(buffer, value);
334 /* write a uint16_t to a buffer in target memory endianness */
335 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
337 if (target->endianness == TARGET_LITTLE_ENDIAN)
338 h_u16_to_le(buffer, value);
339 else
340 h_u16_to_be(buffer, value);
343 /* write a uint8_t to a buffer in target memory endianness */
344 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
346 *buffer = value;
349 /* return a pointer to a configured target; id is name or number */
350 struct target *get_target(const char *id)
352 struct target *target;
354 /* try as tcltarget name */
355 for (target = all_targets; target; target = target->next) {
356 if (target->cmd_name == NULL)
357 continue;
358 if (strcmp(id, target->cmd_name) == 0)
359 return target;
362 /* It's OK to remove this fallback sometime after August 2010 or so */
364 /* no match, try as number */
365 unsigned num;
366 if (parse_uint(id, &num) != ERROR_OK)
367 return NULL;
369 for (target = all_targets; target; target = target->next) {
370 if (target->target_number == (int)num) {
371 LOG_WARNING("use '%s' as target identifier, not '%u'",
372 target->cmd_name, num);
373 return target;
377 return NULL;
380 /* returns a pointer to the n-th configured target */
381 static struct target *get_target_by_num(int num)
383 struct target *target = all_targets;
385 while (target) {
386 if (target->target_number == num) {
387 return target;
389 target = target->next;
392 return NULL;
395 struct target* get_current_target(struct command_context *cmd_ctx)
397 struct target *target = get_target_by_num(cmd_ctx->current_target);
399 if (target == NULL)
401 LOG_ERROR("BUG: current_target out of bounds");
402 exit(-1);
405 return target;
408 int target_poll(struct target *target)
410 int retval;
412 /* We can't poll until after examine */
413 if (!target_was_examined(target))
415 /* Fail silently lest we pollute the log */
416 return ERROR_FAIL;
419 retval = target->type->poll(target);
420 if (retval != ERROR_OK)
421 return retval;
423 if (target->halt_issued)
425 if (target->state == TARGET_HALTED)
427 target->halt_issued = false;
428 } else
430 long long t = timeval_ms() - target->halt_issued_time;
431 if (t>1000)
433 target->halt_issued = false;
434 LOG_INFO("Halt timed out, wake up GDB.");
435 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
440 return ERROR_OK;
443 int target_halt(struct target *target)
445 int retval;
446 /* We can't poll until after examine */
447 if (!target_was_examined(target))
449 LOG_ERROR("Target not examined yet");
450 return ERROR_FAIL;
453 retval = target->type->halt(target);
454 if (retval != ERROR_OK)
455 return retval;
457 target->halt_issued = true;
458 target->halt_issued_time = timeval_ms();
460 return ERROR_OK;
464 * Make the target (re)start executing using its saved execution
465 * context (possibly with some modifications).
467 * @param target Which target should start executing.
468 * @param current True to use the target's saved program counter instead
469 * of the address parameter
470 * @param address Optionally used as the program counter.
471 * @param handle_breakpoints True iff breakpoints at the resumption PC
472 * should be skipped. (For example, maybe execution was stopped by
473 * such a breakpoint, in which case it would be counterprodutive to
474 * let it re-trigger.
475 * @param debug_execution False if all working areas allocated by OpenOCD
476 * should be released and/or restored to their original contents.
477 * (This would for example be true to run some downloaded "helper"
478 * algorithm code, which resides in one such working buffer and uses
479 * another for data storage.)
481 * @todo Resolve the ambiguity about what the "debug_execution" flag
482 * signifies. For example, Target implementations don't agree on how
483 * it relates to invalidation of the register cache, or to whether
484 * breakpoints and watchpoints should be enabled. (It would seem wrong
485 * to enable breakpoints when running downloaded "helper" algorithms
486 * (debug_execution true), since the breakpoints would be set to match
487 * target firmware being debugged, not the helper algorithm.... and
488 * enabling them could cause such helpers to malfunction (for example,
489 * by overwriting data with a breakpoint instruction. On the other
490 * hand the infrastructure for running such helpers might use this
491 * procedure but rely on hardware breakpoint to detect termination.)
493 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
495 int retval;
497 /* We can't poll until after examine */
498 if (!target_was_examined(target))
500 LOG_ERROR("Target not examined yet");
501 return ERROR_FAIL;
504 /* note that resume *must* be asynchronous. The CPU can halt before
505 * we poll. The CPU can even halt at the current PC as a result of
506 * a software breakpoint being inserted by (a bug?) the application.
508 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
509 return retval;
511 return retval;
514 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
516 char buf[100];
517 int retval;
518 Jim_Nvp *n;
519 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
520 if (n->name == NULL) {
521 LOG_ERROR("invalid reset mode");
522 return ERROR_FAIL;
525 /* disable polling during reset to make reset event scripts
526 * more predictable, i.e. dr/irscan & pathmove in events will
527 * not have JTAG operations injected into the middle of a sequence.
529 bool save_poll = jtag_poll_get_enabled();
531 jtag_poll_set_enabled(false);
533 sprintf(buf, "ocd_process_reset %s", n->name);
534 retval = Jim_Eval(cmd_ctx->interp, buf);
536 jtag_poll_set_enabled(save_poll);
538 if (retval != JIM_OK) {
539 Jim_MakeErrorMessage(cmd_ctx->interp);
540 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
541 return ERROR_FAIL;
544 /* We want any events to be processed before the prompt */
545 retval = target_call_timer_callbacks_now();
547 struct target *target;
548 for (target = all_targets; target; target = target->next) {
549 target->type->check_reset(target);
552 return retval;
555 static int identity_virt2phys(struct target *target,
556 uint32_t virtual, uint32_t *physical)
558 *physical = virtual;
559 return ERROR_OK;
562 static int no_mmu(struct target *target, int *enabled)
564 *enabled = 0;
565 return ERROR_OK;
568 static int default_examine(struct target *target)
570 target_set_examined(target);
571 return ERROR_OK;
574 /* no check by default */
575 static int default_check_reset(struct target *target)
577 return ERROR_OK;
580 int target_examine_one(struct target *target)
582 return target->type->examine(target);
585 static int jtag_enable_callback(enum jtag_event event, void *priv)
587 struct target *target = priv;
589 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
590 return ERROR_OK;
592 jtag_unregister_event_callback(jtag_enable_callback, target);
593 return target_examine_one(target);
597 /* Targets that correctly implement init + examine, i.e.
598 * no communication with target during init:
600 * XScale
602 int target_examine(void)
604 int retval = ERROR_OK;
605 struct target *target;
607 for (target = all_targets; target; target = target->next)
609 /* defer examination, but don't skip it */
610 if (!target->tap->enabled) {
611 jtag_register_event_callback(jtag_enable_callback,
612 target);
613 continue;
615 if ((retval = target_examine_one(target)) != ERROR_OK)
616 return retval;
618 return retval;
620 const char *target_type_name(struct target *target)
622 return target->type->name;
625 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
627 if (!target_was_examined(target))
629 LOG_ERROR("Target not examined yet");
630 return ERROR_FAIL;
632 return target->type->write_memory_imp(target, address, size, count, buffer);
635 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
637 if (!target_was_examined(target))
639 LOG_ERROR("Target not examined yet");
640 return ERROR_FAIL;
642 return target->type->read_memory_imp(target, address, size, count, buffer);
645 static int target_soft_reset_halt_imp(struct target *target)
647 if (!target_was_examined(target))
649 LOG_ERROR("Target not examined yet");
650 return ERROR_FAIL;
652 if (!target->type->soft_reset_halt_imp) {
653 LOG_ERROR("Target %s does not support soft_reset_halt",
654 target_name(target));
655 return ERROR_FAIL;
657 return target->type->soft_reset_halt_imp(target);
661 * Downloads a target-specific native code algorithm to the target,
662 * and executes it. * Note that some targets may need to set up, enable,
663 * and tear down a breakpoint (hard or * soft) to detect algorithm
664 * termination, while others may support lower overhead schemes where
665 * soft breakpoints embedded in the algorithm automatically terminate the
666 * algorithm.
668 * @param target used to run the algorithm
669 * @param arch_info target-specific description of the algorithm.
671 int target_run_algorithm(struct target *target,
672 int num_mem_params, struct mem_param *mem_params,
673 int num_reg_params, struct reg_param *reg_param,
674 uint32_t entry_point, uint32_t exit_point,
675 int timeout_ms, void *arch_info)
677 int retval = ERROR_FAIL;
679 if (!target_was_examined(target))
681 LOG_ERROR("Target not examined yet");
682 goto done;
684 if (!target->type->run_algorithm) {
685 LOG_ERROR("Target type '%s' does not support %s",
686 target_type_name(target), __func__);
687 goto done;
690 target->running_alg = true;
691 retval = target->type->run_algorithm(target,
692 num_mem_params, mem_params,
693 num_reg_params, reg_param,
694 entry_point, exit_point, timeout_ms, arch_info);
695 target->running_alg = false;
697 done:
698 return retval;
702 int target_read_memory(struct target *target,
703 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
705 return target->type->read_memory(target, address, size, count, buffer);
708 static int target_read_phys_memory(struct target *target,
709 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
711 return target->type->read_phys_memory(target, address, size, count, buffer);
714 int target_write_memory(struct target *target,
715 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
717 return target->type->write_memory(target, address, size, count, buffer);
720 static int target_write_phys_memory(struct target *target,
721 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
723 return target->type->write_phys_memory(target, address, size, count, buffer);
726 int target_bulk_write_memory(struct target *target,
727 uint32_t address, uint32_t count, const uint8_t *buffer)
729 return target->type->bulk_write_memory(target, address, count, buffer);
732 int target_add_breakpoint(struct target *target,
733 struct breakpoint *breakpoint)
735 if ((target->state != TARGET_HALTED)&&(breakpoint->type!=BKPT_HARD)) {
736 LOG_WARNING("target %s is not halted", target->cmd_name);
737 return ERROR_TARGET_NOT_HALTED;
739 return target->type->add_breakpoint(target, breakpoint);
741 int target_remove_breakpoint(struct target *target,
742 struct breakpoint *breakpoint)
744 return target->type->remove_breakpoint(target, breakpoint);
747 int target_add_watchpoint(struct target *target,
748 struct watchpoint *watchpoint)
750 if (target->state != TARGET_HALTED) {
751 LOG_WARNING("target %s is not halted", target->cmd_name);
752 return ERROR_TARGET_NOT_HALTED;
754 return target->type->add_watchpoint(target, watchpoint);
756 int target_remove_watchpoint(struct target *target,
757 struct watchpoint *watchpoint)
759 return target->type->remove_watchpoint(target, watchpoint);
762 int target_get_gdb_reg_list(struct target *target,
763 struct reg **reg_list[], int *reg_list_size)
765 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
767 int target_step(struct target *target,
768 int current, uint32_t address, int handle_breakpoints)
770 return target->type->step(target, current, address, handle_breakpoints);
775 * Reset the @c examined flag for the given target.
776 * Pure paranoia -- targets are zeroed on allocation.
778 static void target_reset_examined(struct target *target)
780 target->examined = false;
783 static int
784 err_read_phys_memory(struct target *target, uint32_t address,
785 uint32_t size, uint32_t count, uint8_t *buffer)
787 LOG_ERROR("Not implemented: %s", __func__);
788 return ERROR_FAIL;
791 static int
792 err_write_phys_memory(struct target *target, uint32_t address,
793 uint32_t size, uint32_t count, const uint8_t *buffer)
795 LOG_ERROR("Not implemented: %s", __func__);
796 return ERROR_FAIL;
799 static int handle_target(void *priv);
801 static int target_init_one(struct command_context *cmd_ctx,
802 struct target *target)
804 target_reset_examined(target);
806 struct target_type *type = target->type;
807 if (type->examine == NULL)
808 type->examine = default_examine;
810 if (type->check_reset== NULL)
811 type->check_reset = default_check_reset;
813 int retval = type->init_target(cmd_ctx, target);
814 if (ERROR_OK != retval)
816 LOG_ERROR("target '%s' init failed", target_name(target));
817 return retval;
821 * @todo get rid of those *memory_imp() methods, now that all
822 * callers are using target_*_memory() accessors ... and make
823 * sure the "physical" paths handle the same issues.
825 /* a non-invasive way(in terms of patches) to add some code that
826 * runs before the type->write/read_memory implementation
828 type->write_memory_imp = target->type->write_memory;
829 type->write_memory = target_write_memory_imp;
831 type->read_memory_imp = target->type->read_memory;
832 type->read_memory = target_read_memory_imp;
834 type->soft_reset_halt_imp = target->type->soft_reset_halt;
835 type->soft_reset_halt = target_soft_reset_halt_imp;
837 /* Sanity-check MMU support ... stub in what we must, to help
838 * implement it in stages, but warn if we need to do so.
840 if (type->mmu)
842 if (type->write_phys_memory == NULL)
844 LOG_ERROR("type '%s' is missing write_phys_memory",
845 type->name);
846 type->write_phys_memory = err_write_phys_memory;
848 if (type->read_phys_memory == NULL)
850 LOG_ERROR("type '%s' is missing read_phys_memory",
851 type->name);
852 type->read_phys_memory = err_read_phys_memory;
854 if (type->virt2phys == NULL)
856 LOG_ERROR("type '%s' is missing virt2phys", type->name);
857 type->virt2phys = identity_virt2phys;
860 else
862 /* Make sure no-MMU targets all behave the same: make no
863 * distinction between physical and virtual addresses, and
864 * ensure that virt2phys() is always an identity mapping.
866 if (type->write_phys_memory || type->read_phys_memory
867 || type->virt2phys)
869 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
872 type->mmu = no_mmu;
873 type->write_phys_memory = type->write_memory;
874 type->read_phys_memory = type->read_memory;
875 type->virt2phys = identity_virt2phys;
878 if (target->type->read_buffer == NULL)
879 target->type->read_buffer = target_read_buffer_default;
881 if (target->type->write_buffer == NULL)
882 target->type->write_buffer = target_write_buffer_default;
884 return ERROR_OK;
887 static int target_init(struct command_context *cmd_ctx)
889 struct target *target;
890 int retval;
892 for (target = all_targets; target; target = target->next)
894 retval = target_init_one(cmd_ctx, target);
895 if (ERROR_OK != retval)
896 return retval;
899 if (!all_targets)
900 return ERROR_OK;
902 retval = target_register_user_commands(cmd_ctx);
903 if (ERROR_OK != retval)
904 return retval;
906 retval = target_register_timer_callback(&handle_target,
907 polling_interval, 1, cmd_ctx->interp);
908 if (ERROR_OK != retval)
909 return retval;
911 return ERROR_OK;
914 COMMAND_HANDLER(handle_target_init_command)
916 if (CMD_ARGC != 0)
917 return ERROR_COMMAND_SYNTAX_ERROR;
919 static bool target_initialized = false;
920 if (target_initialized)
922 LOG_INFO("'target init' has already been called");
923 return ERROR_OK;
925 target_initialized = true;
927 LOG_DEBUG("Initializing targets...");
928 return target_init(CMD_CTX);
931 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
933 struct target_event_callback **callbacks_p = &target_event_callbacks;
935 if (callback == NULL)
937 return ERROR_INVALID_ARGUMENTS;
940 if (*callbacks_p)
942 while ((*callbacks_p)->next)
943 callbacks_p = &((*callbacks_p)->next);
944 callbacks_p = &((*callbacks_p)->next);
947 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
948 (*callbacks_p)->callback = callback;
949 (*callbacks_p)->priv = priv;
950 (*callbacks_p)->next = NULL;
952 return ERROR_OK;
955 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
957 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
958 struct timeval now;
960 if (callback == NULL)
962 return ERROR_INVALID_ARGUMENTS;
965 if (*callbacks_p)
967 while ((*callbacks_p)->next)
968 callbacks_p = &((*callbacks_p)->next);
969 callbacks_p = &((*callbacks_p)->next);
972 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
973 (*callbacks_p)->callback = callback;
974 (*callbacks_p)->periodic = periodic;
975 (*callbacks_p)->time_ms = time_ms;
977 gettimeofday(&now, NULL);
978 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
979 time_ms -= (time_ms % 1000);
980 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
981 if ((*callbacks_p)->when.tv_usec > 1000000)
983 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
984 (*callbacks_p)->when.tv_sec += 1;
987 (*callbacks_p)->priv = priv;
988 (*callbacks_p)->next = NULL;
990 return ERROR_OK;
993 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
995 struct target_event_callback **p = &target_event_callbacks;
996 struct target_event_callback *c = target_event_callbacks;
998 if (callback == NULL)
1000 return ERROR_INVALID_ARGUMENTS;
1003 while (c)
1005 struct target_event_callback *next = c->next;
1006 if ((c->callback == callback) && (c->priv == priv))
1008 *p = next;
1009 free(c);
1010 return ERROR_OK;
1012 else
1013 p = &(c->next);
1014 c = next;
1017 return ERROR_OK;
1020 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1022 struct target_timer_callback **p = &target_timer_callbacks;
1023 struct target_timer_callback *c = target_timer_callbacks;
1025 if (callback == NULL)
1027 return ERROR_INVALID_ARGUMENTS;
1030 while (c)
1032 struct target_timer_callback *next = c->next;
1033 if ((c->callback == callback) && (c->priv == priv))
1035 *p = next;
1036 free(c);
1037 return ERROR_OK;
1039 else
1040 p = &(c->next);
1041 c = next;
1044 return ERROR_OK;
1047 int target_call_event_callbacks(struct target *target, enum target_event event)
1049 struct target_event_callback *callback = target_event_callbacks;
1050 struct target_event_callback *next_callback;
1052 if (event == TARGET_EVENT_HALTED)
1054 /* execute early halted first */
1055 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1058 LOG_DEBUG("target event %i (%s)",
1059 event,
1060 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1062 target_handle_event(target, event);
1064 while (callback)
1066 next_callback = callback->next;
1067 callback->callback(target, event, callback->priv);
1068 callback = next_callback;
1071 return ERROR_OK;
1074 static int target_timer_callback_periodic_restart(
1075 struct target_timer_callback *cb, struct timeval *now)
1077 int time_ms = cb->time_ms;
1078 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1079 time_ms -= (time_ms % 1000);
1080 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1081 if (cb->when.tv_usec > 1000000)
1083 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1084 cb->when.tv_sec += 1;
1086 return ERROR_OK;
1089 static int target_call_timer_callback(struct target_timer_callback *cb,
1090 struct timeval *now)
1092 cb->callback(cb->priv);
1094 if (cb->periodic)
1095 return target_timer_callback_periodic_restart(cb, now);
1097 return target_unregister_timer_callback(cb->callback, cb->priv);
1100 static int target_call_timer_callbacks_check_time(int checktime)
1102 keep_alive();
1104 struct timeval now;
1105 gettimeofday(&now, NULL);
1107 struct target_timer_callback *callback = target_timer_callbacks;
1108 while (callback)
1110 // cleaning up may unregister and free this callback
1111 struct target_timer_callback *next_callback = callback->next;
1113 bool call_it = callback->callback &&
1114 ((!checktime && callback->periodic) ||
1115 now.tv_sec > callback->when.tv_sec ||
1116 (now.tv_sec == callback->when.tv_sec &&
1117 now.tv_usec >= callback->when.tv_usec));
1119 if (call_it)
1121 int retval = target_call_timer_callback(callback, &now);
1122 if (retval != ERROR_OK)
1123 return retval;
1126 callback = next_callback;
1129 return ERROR_OK;
1132 int target_call_timer_callbacks(void)
1134 return target_call_timer_callbacks_check_time(1);
1137 /* invoke periodic callbacks immediately */
1138 int target_call_timer_callbacks_now(void)
1140 return target_call_timer_callbacks_check_time(0);
1143 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1145 struct working_area *c = target->working_areas;
1146 struct working_area *new_wa = NULL;
1148 /* Reevaluate working area address based on MMU state*/
1149 if (target->working_areas == NULL)
1151 int retval;
1152 int enabled;
1154 retval = target->type->mmu(target, &enabled);
1155 if (retval != ERROR_OK)
1157 return retval;
1160 if (!enabled) {
1161 if (target->working_area_phys_spec) {
1162 LOG_DEBUG("MMU disabled, using physical "
1163 "address for working memory 0x%08x",
1164 (unsigned)target->working_area_phys);
1165 target->working_area = target->working_area_phys;
1166 } else {
1167 LOG_ERROR("No working memory available. "
1168 "Specify -work-area-phys to target.");
1169 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1171 } else {
1172 if (target->working_area_virt_spec) {
1173 LOG_DEBUG("MMU enabled, using virtual "
1174 "address for working memory 0x%08x",
1175 (unsigned)target->working_area_virt);
1176 target->working_area = target->working_area_virt;
1177 } else {
1178 LOG_ERROR("No working memory available. "
1179 "Specify -work-area-virt to target.");
1180 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1185 /* only allocate multiples of 4 byte */
1186 if (size % 4)
1188 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1189 size = (size + 3) & (~3);
1192 /* see if there's already a matching working area */
1193 while (c)
1195 if ((c->free) && (c->size == size))
1197 new_wa = c;
1198 break;
1200 c = c->next;
1203 /* if not, allocate a new one */
1204 if (!new_wa)
1206 struct working_area **p = &target->working_areas;
1207 uint32_t first_free = target->working_area;
1208 uint32_t free_size = target->working_area_size;
1210 c = target->working_areas;
1211 while (c)
1213 first_free += c->size;
1214 free_size -= c->size;
1215 p = &c->next;
1216 c = c->next;
1219 if (free_size < size)
1221 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1224 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1226 new_wa = malloc(sizeof(struct working_area));
1227 new_wa->next = NULL;
1228 new_wa->size = size;
1229 new_wa->address = first_free;
1231 if (target->backup_working_area)
1233 int retval;
1234 new_wa->backup = malloc(new_wa->size);
1235 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1237 free(new_wa->backup);
1238 free(new_wa);
1239 return retval;
1242 else
1244 new_wa->backup = NULL;
1247 /* put new entry in list */
1248 *p = new_wa;
1251 /* mark as used, and return the new (reused) area */
1252 new_wa->free = false;
1253 *area = new_wa;
1255 /* user pointer */
1256 new_wa->user = area;
1258 return ERROR_OK;
1261 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1263 int retval;
1265 retval = target_alloc_working_area_try(target, size, area);
1266 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1268 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1270 return retval;
1274 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1276 if (area->free)
1277 return ERROR_OK;
1279 if (restore && target->backup_working_area)
1281 int retval;
1282 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1283 return retval;
1286 area->free = true;
1288 /* mark user pointer invalid */
1289 *area->user = NULL;
1290 area->user = NULL;
1292 return ERROR_OK;
1295 int target_free_working_area(struct target *target, struct working_area *area)
1297 return target_free_working_area_restore(target, area, 1);
1300 /* free resources and restore memory, if restoring memory fails,
1301 * free up resources anyway
1303 static void target_free_all_working_areas_restore(struct target *target, int restore)
1305 struct working_area *c = target->working_areas;
1307 while (c)
1309 struct working_area *next = c->next;
1310 target_free_working_area_restore(target, c, restore);
1312 if (c->backup)
1313 free(c->backup);
1315 free(c);
1317 c = next;
1320 target->working_areas = NULL;
1323 void target_free_all_working_areas(struct target *target)
1325 target_free_all_working_areas_restore(target, 1);
1328 int target_arch_state(struct target *target)
1330 int retval;
1331 if (target == NULL)
1333 LOG_USER("No target has been configured");
1334 return ERROR_OK;
1337 LOG_USER("target state: %s", target_state_name( target ));
1339 if (target->state != TARGET_HALTED)
1340 return ERROR_OK;
1342 retval = target->type->arch_state(target);
1343 return retval;
1346 /* Single aligned words are guaranteed to use 16 or 32 bit access
1347 * mode respectively, otherwise data is handled as quickly as
1348 * possible
1350 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1352 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1353 (int)size, (unsigned)address);
1355 if (!target_was_examined(target))
1357 LOG_ERROR("Target not examined yet");
1358 return ERROR_FAIL;
1361 if (size == 0) {
1362 return ERROR_OK;
1365 if ((address + size - 1) < address)
1367 /* GDB can request this when e.g. PC is 0xfffffffc*/
1368 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1369 (unsigned)address,
1370 (unsigned)size);
1371 return ERROR_FAIL;
1374 return target->type->write_buffer(target, address, size, buffer);
1377 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1379 int retval = ERROR_OK;
1381 if (((address % 2) == 0) && (size == 2))
1383 return target_write_memory(target, address, 2, 1, buffer);
1386 /* handle unaligned head bytes */
1387 if (address % 4)
1389 uint32_t unaligned = 4 - (address % 4);
1391 if (unaligned > size)
1392 unaligned = size;
1394 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1395 return retval;
1397 buffer += unaligned;
1398 address += unaligned;
1399 size -= unaligned;
1402 /* handle aligned words */
1403 if (size >= 4)
1405 int aligned = size - (size % 4);
1407 /* use bulk writes above a certain limit. This may have to be changed */
1408 if (aligned > 128)
1410 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1411 return retval;
1413 else
1415 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1416 return retval;
1419 buffer += aligned;
1420 address += aligned;
1421 size -= aligned;
1424 /* handle tail writes of less than 4 bytes */
1425 if (size > 0)
1427 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1428 return retval;
1431 return retval;
1434 /* Single aligned words are guaranteed to use 16 or 32 bit access
1435 * mode respectively, otherwise data is handled as quickly as
1436 * possible
1438 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1440 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1441 (int)size, (unsigned)address);
1443 if (!target_was_examined(target))
1445 LOG_ERROR("Target not examined yet");
1446 return ERROR_FAIL;
1449 if (size == 0) {
1450 return ERROR_OK;
1453 if ((address + size - 1) < address)
1455 /* GDB can request this when e.g. PC is 0xfffffffc*/
1456 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1457 address,
1458 size);
1459 return ERROR_FAIL;
1462 return target->type->read_buffer(target, address, size, buffer);
1465 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1467 int retval = ERROR_OK;
1469 if (((address % 2) == 0) && (size == 2))
1471 return target_read_memory(target, address, 2, 1, buffer);
1474 /* handle unaligned head bytes */
1475 if (address % 4)
1477 uint32_t unaligned = 4 - (address % 4);
1479 if (unaligned > size)
1480 unaligned = size;
1482 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1483 return retval;
1485 buffer += unaligned;
1486 address += unaligned;
1487 size -= unaligned;
1490 /* handle aligned words */
1491 if (size >= 4)
1493 int aligned = size - (size % 4);
1495 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1496 return retval;
1498 buffer += aligned;
1499 address += aligned;
1500 size -= aligned;
1503 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1504 if(size >=2)
1506 int aligned = size - (size%2);
1507 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1508 if (retval != ERROR_OK)
1509 return retval;
1511 buffer += aligned;
1512 address += aligned;
1513 size -= aligned;
1515 /* handle tail writes of less than 4 bytes */
1516 if (size > 0)
1518 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1519 return retval;
1522 return ERROR_OK;
1525 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1527 uint8_t *buffer;
1528 int retval;
1529 uint32_t i;
1530 uint32_t checksum = 0;
1531 if (!target_was_examined(target))
1533 LOG_ERROR("Target not examined yet");
1534 return ERROR_FAIL;
1537 if ((retval = target->type->checksum_memory(target, address,
1538 size, &checksum)) != ERROR_OK)
1540 buffer = malloc(size);
1541 if (buffer == NULL)
1543 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1544 return ERROR_INVALID_ARGUMENTS;
1546 retval = target_read_buffer(target, address, size, buffer);
1547 if (retval != ERROR_OK)
1549 free(buffer);
1550 return retval;
1553 /* convert to target endianness */
1554 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1556 uint32_t target_data;
1557 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1558 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1561 retval = image_calculate_checksum(buffer, size, &checksum);
1562 free(buffer);
1565 *crc = checksum;
1567 return retval;
1570 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1572 int retval;
1573 if (!target_was_examined(target))
1575 LOG_ERROR("Target not examined yet");
1576 return ERROR_FAIL;
1579 if (target->type->blank_check_memory == 0)
1580 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1582 retval = target->type->blank_check_memory(target, address, size, blank);
1584 return retval;
1587 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1589 uint8_t value_buf[4];
1590 if (!target_was_examined(target))
1592 LOG_ERROR("Target not examined yet");
1593 return ERROR_FAIL;
1596 int retval = target_read_memory(target, address, 4, 1, value_buf);
1598 if (retval == ERROR_OK)
1600 *value = target_buffer_get_u32(target, value_buf);
1601 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1602 address,
1603 *value);
1605 else
1607 *value = 0x0;
1608 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1609 address);
1612 return retval;
1615 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1617 uint8_t value_buf[2];
1618 if (!target_was_examined(target))
1620 LOG_ERROR("Target not examined yet");
1621 return ERROR_FAIL;
1624 int retval = target_read_memory(target, address, 2, 1, value_buf);
1626 if (retval == ERROR_OK)
1628 *value = target_buffer_get_u16(target, value_buf);
1629 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1630 address,
1631 *value);
1633 else
1635 *value = 0x0;
1636 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1637 address);
1640 return retval;
1643 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1645 int retval = target_read_memory(target, address, 1, 1, value);
1646 if (!target_was_examined(target))
1648 LOG_ERROR("Target not examined yet");
1649 return ERROR_FAIL;
1652 if (retval == ERROR_OK)
1654 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1655 address,
1656 *value);
1658 else
1660 *value = 0x0;
1661 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1662 address);
1665 return retval;
1668 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1670 int retval;
1671 uint8_t value_buf[4];
1672 if (!target_was_examined(target))
1674 LOG_ERROR("Target not examined yet");
1675 return ERROR_FAIL;
1678 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1679 address,
1680 value);
1682 target_buffer_set_u32(target, value_buf, value);
1683 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1685 LOG_DEBUG("failed: %i", retval);
1688 return retval;
1691 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1693 int retval;
1694 uint8_t value_buf[2];
1695 if (!target_was_examined(target))
1697 LOG_ERROR("Target not examined yet");
1698 return ERROR_FAIL;
1701 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1702 address,
1703 value);
1705 target_buffer_set_u16(target, value_buf, value);
1706 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1708 LOG_DEBUG("failed: %i", retval);
1711 return retval;
1714 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1716 int retval;
1717 if (!target_was_examined(target))
1719 LOG_ERROR("Target not examined yet");
1720 return ERROR_FAIL;
1723 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1724 address, value);
1726 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1728 LOG_DEBUG("failed: %i", retval);
1731 return retval;
1734 COMMAND_HANDLER(handle_targets_command)
1736 struct target *target = all_targets;
1738 if (CMD_ARGC == 1)
1740 target = get_target(CMD_ARGV[0]);
1741 if (target == NULL) {
1742 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1743 goto DumpTargets;
1745 if (!target->tap->enabled) {
1746 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1747 "can't be the current target\n",
1748 target->tap->dotted_name);
1749 return ERROR_FAIL;
1752 CMD_CTX->current_target = target->target_number;
1753 return ERROR_OK;
1755 DumpTargets:
1757 target = all_targets;
1758 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1759 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1760 while (target)
1762 const char *state;
1763 char marker = ' ';
1765 if (target->tap->enabled)
1766 state = target_state_name( target );
1767 else
1768 state = "tap-disabled";
1770 if (CMD_CTX->current_target == target->target_number)
1771 marker = '*';
1773 /* keep columns lined up to match the headers above */
1774 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1775 target->target_number,
1776 marker,
1777 target_name(target),
1778 target_type_name(target),
1779 Jim_Nvp_value2name_simple(nvp_target_endian,
1780 target->endianness)->name,
1781 target->tap->dotted_name,
1782 state);
1783 target = target->next;
1786 return ERROR_OK;
1789 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1791 static int powerDropout;
1792 static int srstAsserted;
1794 static int runPowerRestore;
1795 static int runPowerDropout;
1796 static int runSrstAsserted;
1797 static int runSrstDeasserted;
1799 static int sense_handler(void)
1801 static int prevSrstAsserted = 0;
1802 static int prevPowerdropout = 0;
1804 int retval;
1805 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1806 return retval;
1808 int powerRestored;
1809 powerRestored = prevPowerdropout && !powerDropout;
1810 if (powerRestored)
1812 runPowerRestore = 1;
1815 long long current = timeval_ms();
1816 static long long lastPower = 0;
1817 int waitMore = lastPower + 2000 > current;
1818 if (powerDropout && !waitMore)
1820 runPowerDropout = 1;
1821 lastPower = current;
1824 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1825 return retval;
1827 int srstDeasserted;
1828 srstDeasserted = prevSrstAsserted && !srstAsserted;
1830 static long long lastSrst = 0;
1831 waitMore = lastSrst + 2000 > current;
1832 if (srstDeasserted && !waitMore)
1834 runSrstDeasserted = 1;
1835 lastSrst = current;
1838 if (!prevSrstAsserted && srstAsserted)
1840 runSrstAsserted = 1;
1843 prevSrstAsserted = srstAsserted;
1844 prevPowerdropout = powerDropout;
1846 if (srstDeasserted || powerRestored)
1848 /* Other than logging the event we can't do anything here.
1849 * Issuing a reset is a particularly bad idea as we might
1850 * be inside a reset already.
1854 return ERROR_OK;
1857 static int backoff_times = 0;
1858 static int backoff_count = 0;
1860 /* process target state changes */
1861 static int handle_target(void *priv)
1863 Jim_Interp *interp = (Jim_Interp *)priv;
1864 int retval = ERROR_OK;
1866 if (!is_jtag_poll_safe())
1868 /* polling is disabled currently */
1869 return ERROR_OK;
1872 /* we do not want to recurse here... */
1873 static int recursive = 0;
1874 if (! recursive)
1876 recursive = 1;
1877 sense_handler();
1878 /* danger! running these procedures can trigger srst assertions and power dropouts.
1879 * We need to avoid an infinite loop/recursion here and we do that by
1880 * clearing the flags after running these events.
1882 int did_something = 0;
1883 if (runSrstAsserted)
1885 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1886 Jim_Eval(interp, "srst_asserted");
1887 did_something = 1;
1889 if (runSrstDeasserted)
1891 Jim_Eval(interp, "srst_deasserted");
1892 did_something = 1;
1894 if (runPowerDropout)
1896 LOG_INFO("Power dropout detected, running power_dropout proc.");
1897 Jim_Eval(interp, "power_dropout");
1898 did_something = 1;
1900 if (runPowerRestore)
1902 Jim_Eval(interp, "power_restore");
1903 did_something = 1;
1906 if (did_something)
1908 /* clear detect flags */
1909 sense_handler();
1912 /* clear action flags */
1914 runSrstAsserted = 0;
1915 runSrstDeasserted = 0;
1916 runPowerRestore = 0;
1917 runPowerDropout = 0;
1919 recursive = 0;
1922 if (backoff_times > backoff_count)
1924 /* do not poll this time as we failed previously */
1925 backoff_count++;
1926 return ERROR_OK;
1928 backoff_count = 0;
1930 /* Poll targets for state changes unless that's globally disabled.
1931 * Skip targets that are currently disabled.
1933 for (struct target *target = all_targets;
1934 is_jtag_poll_safe() && target;
1935 target = target->next)
1937 if (!target->tap->enabled)
1938 continue;
1940 /* only poll target if we've got power and srst isn't asserted */
1941 if (!powerDropout && !srstAsserted)
1943 /* polling may fail silently until the target has been examined */
1944 if ((retval = target_poll(target)) != ERROR_OK)
1946 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1947 if (backoff_times * polling_interval < 5000)
1949 backoff_times *= 2;
1950 backoff_times++;
1952 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1954 /* Tell GDB to halt the debugger. This allows the user to
1955 * run monitor commands to handle the situation.
1957 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1958 return retval;
1960 /* Since we succeeded, we reset backoff count */
1961 if (backoff_times > 0)
1963 LOG_USER("Polling succeeded again");
1965 backoff_times = 0;
1969 return retval;
1972 COMMAND_HANDLER(handle_reg_command)
1974 struct target *target;
1975 struct reg *reg = NULL;
1976 unsigned count = 0;
1977 char *value;
1979 LOG_DEBUG("-");
1981 target = get_current_target(CMD_CTX);
1983 /* list all available registers for the current target */
1984 if (CMD_ARGC == 0)
1986 struct reg_cache *cache = target->reg_cache;
1988 count = 0;
1989 while (cache)
1991 unsigned i;
1993 command_print(CMD_CTX, "===== %s", cache->name);
1995 for (i = 0, reg = cache->reg_list;
1996 i < cache->num_regs;
1997 i++, reg++, count++)
1999 /* only print cached values if they are valid */
2000 if (reg->valid) {
2001 value = buf_to_str(reg->value,
2002 reg->size, 16);
2003 command_print(CMD_CTX,
2004 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2005 count, reg->name,
2006 reg->size, value,
2007 reg->dirty
2008 ? " (dirty)"
2009 : "");
2010 free(value);
2011 } else {
2012 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2013 count, reg->name,
2014 reg->size) ;
2017 cache = cache->next;
2020 return ERROR_OK;
2023 /* access a single register by its ordinal number */
2024 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
2026 unsigned num;
2027 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2029 struct reg_cache *cache = target->reg_cache;
2030 count = 0;
2031 while (cache)
2033 unsigned i;
2034 for (i = 0; i < cache->num_regs; i++)
2036 if (count++ == num)
2038 reg = &cache->reg_list[i];
2039 break;
2042 if (reg)
2043 break;
2044 cache = cache->next;
2047 if (!reg)
2049 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2050 return ERROR_OK;
2052 } else /* access a single register by its name */
2054 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2056 if (!reg)
2058 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2059 return ERROR_OK;
2063 /* display a register */
2064 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2066 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2067 reg->valid = 0;
2069 if (reg->valid == 0)
2071 reg->type->get(reg);
2073 value = buf_to_str(reg->value, reg->size, 16);
2074 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2075 free(value);
2076 return ERROR_OK;
2079 /* set register value */
2080 if (CMD_ARGC == 2)
2082 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2083 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2085 reg->type->set(reg, buf);
2087 value = buf_to_str(reg->value, reg->size, 16);
2088 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2089 free(value);
2091 free(buf);
2093 return ERROR_OK;
2096 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2098 return ERROR_OK;
2101 COMMAND_HANDLER(handle_poll_command)
2103 int retval = ERROR_OK;
2104 struct target *target = get_current_target(CMD_CTX);
2106 if (CMD_ARGC == 0)
2108 command_print(CMD_CTX, "background polling: %s",
2109 jtag_poll_get_enabled() ? "on" : "off");
2110 command_print(CMD_CTX, "TAP: %s (%s)",
2111 target->tap->dotted_name,
2112 target->tap->enabled ? "enabled" : "disabled");
2113 if (!target->tap->enabled)
2114 return ERROR_OK;
2115 if ((retval = target_poll(target)) != ERROR_OK)
2116 return retval;
2117 if ((retval = target_arch_state(target)) != ERROR_OK)
2118 return retval;
2120 else if (CMD_ARGC == 1)
2122 bool enable;
2123 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2124 jtag_poll_set_enabled(enable);
2126 else
2128 return ERROR_COMMAND_SYNTAX_ERROR;
2131 return retval;
2134 COMMAND_HANDLER(handle_wait_halt_command)
2136 if (CMD_ARGC > 1)
2137 return ERROR_COMMAND_SYNTAX_ERROR;
2139 unsigned ms = 5000;
2140 if (1 == CMD_ARGC)
2142 int retval = parse_uint(CMD_ARGV[0], &ms);
2143 if (ERROR_OK != retval)
2145 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2146 return ERROR_COMMAND_SYNTAX_ERROR;
2148 // convert seconds (given) to milliseconds (needed)
2149 ms *= 1000;
2152 struct target *target = get_current_target(CMD_CTX);
2153 return target_wait_state(target, TARGET_HALTED, ms);
2156 /* wait for target state to change. The trick here is to have a low
2157 * latency for short waits and not to suck up all the CPU time
2158 * on longer waits.
2160 * After 500ms, keep_alive() is invoked
2162 int target_wait_state(struct target *target, enum target_state state, int ms)
2164 int retval;
2165 long long then = 0, cur;
2166 int once = 1;
2168 for (;;)
2170 if ((retval = target_poll(target)) != ERROR_OK)
2171 return retval;
2172 if (target->state == state)
2174 break;
2176 cur = timeval_ms();
2177 if (once)
2179 once = 0;
2180 then = timeval_ms();
2181 LOG_DEBUG("waiting for target %s...",
2182 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2185 if (cur-then > 500)
2187 keep_alive();
2190 if ((cur-then) > ms)
2192 LOG_ERROR("timed out while waiting for target %s",
2193 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2194 return ERROR_FAIL;
2198 return ERROR_OK;
2201 COMMAND_HANDLER(handle_halt_command)
2203 LOG_DEBUG("-");
2205 struct target *target = get_current_target(CMD_CTX);
2206 int retval = target_halt(target);
2207 if (ERROR_OK != retval)
2208 return retval;
2210 if (CMD_ARGC == 1)
2212 unsigned wait_local;
2213 retval = parse_uint(CMD_ARGV[0], &wait_local);
2214 if (ERROR_OK != retval)
2215 return ERROR_COMMAND_SYNTAX_ERROR;
2216 if (!wait_local)
2217 return ERROR_OK;
2220 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2223 COMMAND_HANDLER(handle_soft_reset_halt_command)
2225 struct target *target = get_current_target(CMD_CTX);
2227 LOG_USER("requesting target halt and executing a soft reset");
2229 target->type->soft_reset_halt(target);
2231 return ERROR_OK;
2234 COMMAND_HANDLER(handle_reset_command)
2236 if (CMD_ARGC > 1)
2237 return ERROR_COMMAND_SYNTAX_ERROR;
2239 enum target_reset_mode reset_mode = RESET_RUN;
2240 if (CMD_ARGC == 1)
2242 const Jim_Nvp *n;
2243 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2244 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2245 return ERROR_COMMAND_SYNTAX_ERROR;
2247 reset_mode = n->value;
2250 /* reset *all* targets */
2251 return target_process_reset(CMD_CTX, reset_mode);
2255 COMMAND_HANDLER(handle_resume_command)
2257 int current = 1;
2258 if (CMD_ARGC > 1)
2259 return ERROR_COMMAND_SYNTAX_ERROR;
2261 struct target *target = get_current_target(CMD_CTX);
2262 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2264 /* with no CMD_ARGV, resume from current pc, addr = 0,
2265 * with one arguments, addr = CMD_ARGV[0],
2266 * handle breakpoints, not debugging */
2267 uint32_t addr = 0;
2268 if (CMD_ARGC == 1)
2270 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2271 current = 0;
2274 return target_resume(target, current, addr, 1, 0);
2277 COMMAND_HANDLER(handle_step_command)
2279 if (CMD_ARGC > 1)
2280 return ERROR_COMMAND_SYNTAX_ERROR;
2282 LOG_DEBUG("-");
2284 /* with no CMD_ARGV, step from current pc, addr = 0,
2285 * with one argument addr = CMD_ARGV[0],
2286 * handle breakpoints, debugging */
2287 uint32_t addr = 0;
2288 int current_pc = 1;
2289 if (CMD_ARGC == 1)
2291 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2292 current_pc = 0;
2295 struct target *target = get_current_target(CMD_CTX);
2297 return target->type->step(target, current_pc, addr, 1);
2300 static void handle_md_output(struct command_context *cmd_ctx,
2301 struct target *target, uint32_t address, unsigned size,
2302 unsigned count, const uint8_t *buffer)
2304 const unsigned line_bytecnt = 32;
2305 unsigned line_modulo = line_bytecnt / size;
2307 char output[line_bytecnt * 4 + 1];
2308 unsigned output_len = 0;
2310 const char *value_fmt;
2311 switch (size) {
2312 case 4: value_fmt = "%8.8x "; break;
2313 case 2: value_fmt = "%4.4x "; break;
2314 case 1: value_fmt = "%2.2x "; break;
2315 default:
2316 /* "can't happen", caller checked */
2317 LOG_ERROR("invalid memory read size: %u", size);
2318 return;
2321 for (unsigned i = 0; i < count; i++)
2323 if (i % line_modulo == 0)
2325 output_len += snprintf(output + output_len,
2326 sizeof(output) - output_len,
2327 "0x%8.8x: ",
2328 (unsigned)(address + (i*size)));
2331 uint32_t value = 0;
2332 const uint8_t *value_ptr = buffer + i * size;
2333 switch (size) {
2334 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2335 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2336 case 1: value = *value_ptr;
2338 output_len += snprintf(output + output_len,
2339 sizeof(output) - output_len,
2340 value_fmt, value);
2342 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2344 command_print(cmd_ctx, "%s", output);
2345 output_len = 0;
2350 COMMAND_HANDLER(handle_md_command)
2352 if (CMD_ARGC < 1)
2353 return ERROR_COMMAND_SYNTAX_ERROR;
2355 unsigned size = 0;
2356 switch (CMD_NAME[2]) {
2357 case 'w': size = 4; break;
2358 case 'h': size = 2; break;
2359 case 'b': size = 1; break;
2360 default: return ERROR_COMMAND_SYNTAX_ERROR;
2363 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2364 int (*fn)(struct target *target,
2365 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2366 if (physical)
2368 CMD_ARGC--;
2369 CMD_ARGV++;
2370 fn=target_read_phys_memory;
2371 } else
2373 fn=target_read_memory;
2375 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2377 return ERROR_COMMAND_SYNTAX_ERROR;
2380 uint32_t address;
2381 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2383 unsigned count = 1;
2384 if (CMD_ARGC == 2)
2385 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2387 uint8_t *buffer = calloc(count, size);
2389 struct target *target = get_current_target(CMD_CTX);
2390 int retval = fn(target, address, size, count, buffer);
2391 if (ERROR_OK == retval)
2392 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2394 free(buffer);
2396 return retval;
2399 typedef int (*target_write_fn)(struct target *target,
2400 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2402 static int target_write_memory_fast(struct target *target,
2403 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2405 return target_write_buffer(target, address, size * count, buffer);
2408 static int target_fill_mem(struct target *target,
2409 uint32_t address,
2410 target_write_fn fn,
2411 unsigned data_size,
2412 /* value */
2413 uint32_t b,
2414 /* count */
2415 unsigned c)
2417 /* We have to write in reasonably large chunks to be able
2418 * to fill large memory areas with any sane speed */
2419 const unsigned chunk_size = 16384;
2420 uint8_t *target_buf = malloc(chunk_size * data_size);
2421 if (target_buf == NULL)
2423 LOG_ERROR("Out of memory");
2424 return ERROR_FAIL;
2427 for (unsigned i = 0; i < chunk_size; i ++)
2429 switch (data_size)
2431 case 4:
2432 target_buffer_set_u32(target, target_buf + i*data_size, b);
2433 break;
2434 case 2:
2435 target_buffer_set_u16(target, target_buf + i*data_size, b);
2436 break;
2437 case 1:
2438 target_buffer_set_u8(target, target_buf + i*data_size, b);
2439 break;
2440 default:
2441 exit(-1);
2445 int retval = ERROR_OK;
2447 for (unsigned x = 0; x < c; x += chunk_size)
2449 unsigned current;
2450 current = c - x;
2451 if (current > chunk_size)
2453 current = chunk_size;
2455 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2456 if (retval != ERROR_OK)
2458 break;
2460 /* avoid GDB timeouts */
2461 keep_alive();
2463 free(target_buf);
2465 return retval;
2469 COMMAND_HANDLER(handle_mw_command)
2471 if (CMD_ARGC < 2)
2473 return ERROR_COMMAND_SYNTAX_ERROR;
2475 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2476 target_write_fn fn;
2477 if (physical)
2479 CMD_ARGC--;
2480 CMD_ARGV++;
2481 fn=target_write_phys_memory;
2482 } else
2484 fn = target_write_memory_fast;
2486 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2487 return ERROR_COMMAND_SYNTAX_ERROR;
2489 uint32_t address;
2490 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2492 uint32_t value;
2493 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2495 unsigned count = 1;
2496 if (CMD_ARGC == 3)
2497 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2499 struct target *target = get_current_target(CMD_CTX);
2500 unsigned wordsize;
2501 switch (CMD_NAME[2])
2503 case 'w':
2504 wordsize = 4;
2505 break;
2506 case 'h':
2507 wordsize = 2;
2508 break;
2509 case 'b':
2510 wordsize = 1;
2511 break;
2512 default:
2513 return ERROR_COMMAND_SYNTAX_ERROR;
2516 return target_fill_mem(target, address, fn, wordsize, value, count);
2519 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2520 uint32_t *min_address, uint32_t *max_address)
2522 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2523 return ERROR_COMMAND_SYNTAX_ERROR;
2525 /* a base address isn't always necessary,
2526 * default to 0x0 (i.e. don't relocate) */
2527 if (CMD_ARGC >= 2)
2529 uint32_t addr;
2530 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2531 image->base_address = addr;
2532 image->base_address_set = 1;
2534 else
2535 image->base_address_set = 0;
2537 image->start_address_set = 0;
2539 if (CMD_ARGC >= 4)
2541 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2543 if (CMD_ARGC == 5)
2545 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2546 // use size (given) to find max (required)
2547 *max_address += *min_address;
2550 if (*min_address > *max_address)
2551 return ERROR_COMMAND_SYNTAX_ERROR;
2553 return ERROR_OK;
2556 COMMAND_HANDLER(handle_load_image_command)
2558 uint8_t *buffer;
2559 size_t buf_cnt;
2560 uint32_t image_size;
2561 uint32_t min_address = 0;
2562 uint32_t max_address = 0xffffffff;
2563 int i;
2564 struct image image;
2566 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2567 &image, &min_address, &max_address);
2568 if (ERROR_OK != retval)
2569 return retval;
2571 struct target *target = get_current_target(CMD_CTX);
2573 struct duration bench;
2574 duration_start(&bench);
2576 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2578 return ERROR_OK;
2581 image_size = 0x0;
2582 retval = ERROR_OK;
2583 for (i = 0; i < image.num_sections; i++)
2585 buffer = malloc(image.sections[i].size);
2586 if (buffer == NULL)
2588 command_print(CMD_CTX,
2589 "error allocating buffer for section (%d bytes)",
2590 (int)(image.sections[i].size));
2591 break;
2594 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2596 free(buffer);
2597 break;
2600 uint32_t offset = 0;
2601 uint32_t length = buf_cnt;
2603 /* DANGER!!! beware of unsigned comparision here!!! */
2605 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2606 (image.sections[i].base_address < max_address))
2608 if (image.sections[i].base_address < min_address)
2610 /* clip addresses below */
2611 offset += min_address-image.sections[i].base_address;
2612 length -= offset;
2615 if (image.sections[i].base_address + buf_cnt > max_address)
2617 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2620 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2622 free(buffer);
2623 break;
2625 image_size += length;
2626 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2627 (unsigned int)length,
2628 image.sections[i].base_address + offset);
2631 free(buffer);
2634 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2636 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2637 "in %fs (%0.3f KiB/s)", image_size,
2638 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2641 image_close(&image);
2643 return retval;
2647 COMMAND_HANDLER(handle_dump_image_command)
2649 struct fileio fileio;
2650 uint8_t buffer[560];
2651 int retval, retvaltemp;
2652 uint32_t address, size;
2653 struct duration bench;
2654 struct target *target = get_current_target(CMD_CTX);
2656 if (CMD_ARGC != 3)
2657 return ERROR_COMMAND_SYNTAX_ERROR;
2659 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2660 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2662 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2663 if (retval != ERROR_OK)
2664 return retval;
2666 duration_start(&bench);
2668 retval = ERROR_OK;
2669 while (size > 0)
2671 size_t size_written;
2672 uint32_t this_run_size = (size > 560) ? 560 : size;
2673 retval = target_read_buffer(target, address, this_run_size, buffer);
2674 if (retval != ERROR_OK)
2676 break;
2679 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2680 if (retval != ERROR_OK)
2682 break;
2685 size -= this_run_size;
2686 address += this_run_size;
2689 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2691 int filesize;
2692 retval = fileio_size(&fileio, &filesize);
2693 if (retval != ERROR_OK)
2694 return retval;
2695 command_print(CMD_CTX,
2696 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2697 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2700 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2701 return retvaltemp;
2703 return retval;
2706 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2708 uint8_t *buffer;
2709 size_t buf_cnt;
2710 uint32_t image_size;
2711 int i;
2712 int retval;
2713 uint32_t checksum = 0;
2714 uint32_t mem_checksum = 0;
2716 struct image image;
2718 struct target *target = get_current_target(CMD_CTX);
2720 if (CMD_ARGC < 1)
2722 return ERROR_COMMAND_SYNTAX_ERROR;
2725 if (!target)
2727 LOG_ERROR("no target selected");
2728 return ERROR_FAIL;
2731 struct duration bench;
2732 duration_start(&bench);
2734 if (CMD_ARGC >= 2)
2736 uint32_t addr;
2737 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2738 image.base_address = addr;
2739 image.base_address_set = 1;
2741 else
2743 image.base_address_set = 0;
2744 image.base_address = 0x0;
2747 image.start_address_set = 0;
2749 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2751 return retval;
2754 image_size = 0x0;
2755 int diffs = 0;
2756 retval = ERROR_OK;
2757 for (i = 0; i < image.num_sections; i++)
2759 buffer = malloc(image.sections[i].size);
2760 if (buffer == NULL)
2762 command_print(CMD_CTX,
2763 "error allocating buffer for section (%d bytes)",
2764 (int)(image.sections[i].size));
2765 break;
2767 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2769 free(buffer);
2770 break;
2773 if (verify)
2775 /* calculate checksum of image */
2776 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2777 if (retval != ERROR_OK)
2779 free(buffer);
2780 break;
2783 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2784 if (retval != ERROR_OK)
2786 free(buffer);
2787 break;
2790 if (checksum != mem_checksum)
2792 /* failed crc checksum, fall back to a binary compare */
2793 uint8_t *data;
2795 if (diffs == 0)
2797 LOG_ERROR("checksum mismatch - attempting binary compare");
2800 data = (uint8_t*)malloc(buf_cnt);
2802 /* Can we use 32bit word accesses? */
2803 int size = 1;
2804 int count = buf_cnt;
2805 if ((count % 4) == 0)
2807 size *= 4;
2808 count /= 4;
2810 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2811 if (retval == ERROR_OK)
2813 uint32_t t;
2814 for (t = 0; t < buf_cnt; t++)
2816 if (data[t] != buffer[t])
2818 command_print(CMD_CTX,
2819 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2820 diffs,
2821 (unsigned)(t + image.sections[i].base_address),
2822 data[t],
2823 buffer[t]);
2824 if (diffs++ >= 127)
2826 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2827 free(data);
2828 free(buffer);
2829 goto done;
2832 keep_alive();
2835 free(data);
2837 } else
2839 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2840 image.sections[i].base_address,
2841 buf_cnt);
2844 free(buffer);
2845 image_size += buf_cnt;
2847 if (diffs > 0)
2849 command_print(CMD_CTX, "No more differences found.");
2851 done:
2852 if (diffs > 0)
2854 retval = ERROR_FAIL;
2856 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2858 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2859 "in %fs (%0.3f KiB/s)", image_size,
2860 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2863 image_close(&image);
2865 return retval;
2868 COMMAND_HANDLER(handle_verify_image_command)
2870 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2873 COMMAND_HANDLER(handle_test_image_command)
2875 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2878 static int handle_bp_command_list(struct command_context *cmd_ctx)
2880 struct target *target = get_current_target(cmd_ctx);
2881 struct breakpoint *breakpoint = target->breakpoints;
2882 while (breakpoint)
2884 if (breakpoint->type == BKPT_SOFT)
2886 char* buf = buf_to_str(breakpoint->orig_instr,
2887 breakpoint->length, 16);
2888 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2889 breakpoint->address,
2890 breakpoint->length,
2891 breakpoint->set, buf);
2892 free(buf);
2894 else
2896 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2897 breakpoint->address,
2898 breakpoint->length, breakpoint->set);
2901 breakpoint = breakpoint->next;
2903 return ERROR_OK;
2906 static int handle_bp_command_set(struct command_context *cmd_ctx,
2907 uint32_t addr, uint32_t length, int hw)
2909 struct target *target = get_current_target(cmd_ctx);
2910 int retval = breakpoint_add(target, addr, length, hw);
2911 if (ERROR_OK == retval)
2912 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2913 else
2914 LOG_ERROR("Failure setting breakpoint");
2915 return retval;
2918 COMMAND_HANDLER(handle_bp_command)
2920 if (CMD_ARGC == 0)
2921 return handle_bp_command_list(CMD_CTX);
2923 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2925 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2926 return ERROR_COMMAND_SYNTAX_ERROR;
2929 uint32_t addr;
2930 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2931 uint32_t length;
2932 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2934 int hw = BKPT_SOFT;
2935 if (CMD_ARGC == 3)
2937 if (strcmp(CMD_ARGV[2], "hw") == 0)
2938 hw = BKPT_HARD;
2939 else
2940 return ERROR_COMMAND_SYNTAX_ERROR;
2943 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2946 COMMAND_HANDLER(handle_rbp_command)
2948 if (CMD_ARGC != 1)
2949 return ERROR_COMMAND_SYNTAX_ERROR;
2951 uint32_t addr;
2952 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2954 struct target *target = get_current_target(CMD_CTX);
2955 breakpoint_remove(target, addr);
2957 return ERROR_OK;
2960 COMMAND_HANDLER(handle_wp_command)
2962 struct target *target = get_current_target(CMD_CTX);
2964 if (CMD_ARGC == 0)
2966 struct watchpoint *watchpoint = target->watchpoints;
2968 while (watchpoint)
2970 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2971 ", len: 0x%8.8" PRIx32
2972 ", r/w/a: %i, value: 0x%8.8" PRIx32
2973 ", mask: 0x%8.8" PRIx32,
2974 watchpoint->address,
2975 watchpoint->length,
2976 (int)watchpoint->rw,
2977 watchpoint->value,
2978 watchpoint->mask);
2979 watchpoint = watchpoint->next;
2981 return ERROR_OK;
2984 enum watchpoint_rw type = WPT_ACCESS;
2985 uint32_t addr = 0;
2986 uint32_t length = 0;
2987 uint32_t data_value = 0x0;
2988 uint32_t data_mask = 0xffffffff;
2990 switch (CMD_ARGC)
2992 case 5:
2993 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2994 // fall through
2995 case 4:
2996 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2997 // fall through
2998 case 3:
2999 switch (CMD_ARGV[2][0])
3001 case 'r':
3002 type = WPT_READ;
3003 break;
3004 case 'w':
3005 type = WPT_WRITE;
3006 break;
3007 case 'a':
3008 type = WPT_ACCESS;
3009 break;
3010 default:
3011 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3012 return ERROR_COMMAND_SYNTAX_ERROR;
3014 // fall through
3015 case 2:
3016 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3017 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3018 break;
3020 default:
3021 command_print(CMD_CTX, "usage: wp [address length "
3022 "[(r|w|a) [value [mask]]]]");
3023 return ERROR_COMMAND_SYNTAX_ERROR;
3026 int retval = watchpoint_add(target, addr, length, type,
3027 data_value, data_mask);
3028 if (ERROR_OK != retval)
3029 LOG_ERROR("Failure setting watchpoints");
3031 return retval;
3034 COMMAND_HANDLER(handle_rwp_command)
3036 if (CMD_ARGC != 1)
3037 return ERROR_COMMAND_SYNTAX_ERROR;
3039 uint32_t addr;
3040 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3042 struct target *target = get_current_target(CMD_CTX);
3043 watchpoint_remove(target, addr);
3045 return ERROR_OK;
3050 * Translate a virtual address to a physical address.
3052 * The low-level target implementation must have logged a detailed error
3053 * which is forwarded to telnet/GDB session.
3055 COMMAND_HANDLER(handle_virt2phys_command)
3057 if (CMD_ARGC != 1)
3058 return ERROR_COMMAND_SYNTAX_ERROR;
3060 uint32_t va;
3061 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3062 uint32_t pa;
3064 struct target *target = get_current_target(CMD_CTX);
3065 int retval = target->type->virt2phys(target, va, &pa);
3066 if (retval == ERROR_OK)
3067 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3069 return retval;
3072 static void writeData(FILE *f, const void *data, size_t len)
3074 size_t written = fwrite(data, 1, len, f);
3075 if (written != len)
3076 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3079 static void writeLong(FILE *f, int l)
3081 int i;
3082 for (i = 0; i < 4; i++)
3084 char c = (l >> (i*8))&0xff;
3085 writeData(f, &c, 1);
3090 static void writeString(FILE *f, char *s)
3092 writeData(f, s, strlen(s));
3095 /* Dump a gmon.out histogram file. */
3096 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3098 uint32_t i;
3099 FILE *f = fopen(filename, "w");
3100 if (f == NULL)
3101 return;
3102 writeString(f, "gmon");
3103 writeLong(f, 0x00000001); /* Version */
3104 writeLong(f, 0); /* padding */
3105 writeLong(f, 0); /* padding */
3106 writeLong(f, 0); /* padding */
3108 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3109 writeData(f, &zero, 1);
3111 /* figure out bucket size */
3112 uint32_t min = samples[0];
3113 uint32_t max = samples[0];
3114 for (i = 0; i < sampleNum; i++)
3116 if (min > samples[i])
3118 min = samples[i];
3120 if (max < samples[i])
3122 max = samples[i];
3126 int addressSpace = (max-min + 1);
3128 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3129 uint32_t length = addressSpace;
3130 if (length > maxBuckets)
3132 length = maxBuckets;
3134 int *buckets = malloc(sizeof(int)*length);
3135 if (buckets == NULL)
3137 fclose(f);
3138 return;
3140 memset(buckets, 0, sizeof(int)*length);
3141 for (i = 0; i < sampleNum;i++)
3143 uint32_t address = samples[i];
3144 long long a = address-min;
3145 long long b = length-1;
3146 long long c = addressSpace-1;
3147 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3148 buckets[index_t]++;
3151 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3152 writeLong(f, min); /* low_pc */
3153 writeLong(f, max); /* high_pc */
3154 writeLong(f, length); /* # of samples */
3155 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3156 writeString(f, "seconds");
3157 for (i = 0; i < (15-strlen("seconds")); i++)
3158 writeData(f, &zero, 1);
3159 writeString(f, "s");
3161 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3163 char *data = malloc(2*length);
3164 if (data != NULL)
3166 for (i = 0; i < length;i++)
3168 int val;
3169 val = buckets[i];
3170 if (val > 65535)
3172 val = 65535;
3174 data[i*2]=val&0xff;
3175 data[i*2 + 1]=(val >> 8)&0xff;
3177 free(buckets);
3178 writeData(f, data, length * 2);
3179 free(data);
3180 } else
3182 free(buckets);
3185 fclose(f);
3188 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3189 * which will be used as a random sampling of PC */
3190 COMMAND_HANDLER(handle_profile_command)
3192 struct target *target = get_current_target(CMD_CTX);
3193 struct timeval timeout, now;
3195 gettimeofday(&timeout, NULL);
3196 if (CMD_ARGC != 2)
3198 return ERROR_COMMAND_SYNTAX_ERROR;
3200 unsigned offset;
3201 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3203 timeval_add_time(&timeout, offset, 0);
3206 * @todo: Some cores let us sample the PC without the
3207 * annoying halt/resume step; for example, ARMv7 PCSR.
3208 * Provide a way to use that more efficient mechanism.
3211 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3213 static const int maxSample = 10000;
3214 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3215 if (samples == NULL)
3216 return ERROR_OK;
3218 int numSamples = 0;
3219 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3220 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3222 for (;;)
3224 int retval;
3225 target_poll(target);
3226 if (target->state == TARGET_HALTED)
3228 uint32_t t=*((uint32_t *)reg->value);
3229 samples[numSamples++]=t;
3230 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3231 target_poll(target);
3232 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3233 } else if (target->state == TARGET_RUNNING)
3235 /* We want to quickly sample the PC. */
3236 if ((retval = target_halt(target)) != ERROR_OK)
3238 free(samples);
3239 return retval;
3241 } else
3243 command_print(CMD_CTX, "Target not halted or running");
3244 retval = ERROR_OK;
3245 break;
3247 if (retval != ERROR_OK)
3249 break;
3252 gettimeofday(&now, NULL);
3253 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3255 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3256 if ((retval = target_poll(target)) != ERROR_OK)
3258 free(samples);
3259 return retval;
3261 if (target->state == TARGET_HALTED)
3263 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3265 if ((retval = target_poll(target)) != ERROR_OK)
3267 free(samples);
3268 return retval;
3270 writeGmon(samples, numSamples, CMD_ARGV[1]);
3271 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3272 break;
3275 free(samples);
3277 return ERROR_OK;
3280 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3282 char *namebuf;
3283 Jim_Obj *nameObjPtr, *valObjPtr;
3284 int result;
3286 namebuf = alloc_printf("%s(%d)", varname, idx);
3287 if (!namebuf)
3288 return JIM_ERR;
3290 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3291 valObjPtr = Jim_NewIntObj(interp, val);
3292 if (!nameObjPtr || !valObjPtr)
3294 free(namebuf);
3295 return JIM_ERR;
3298 Jim_IncrRefCount(nameObjPtr);
3299 Jim_IncrRefCount(valObjPtr);
3300 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3301 Jim_DecrRefCount(interp, nameObjPtr);
3302 Jim_DecrRefCount(interp, valObjPtr);
3303 free(namebuf);
3304 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3305 return result;
3308 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3310 struct command_context *context;
3311 struct target *target;
3313 context = current_command_context(interp);
3314 assert (context != NULL);
3316 target = get_current_target(context);
3317 if (target == NULL)
3319 LOG_ERROR("mem2array: no current target");
3320 return JIM_ERR;
3323 return target_mem2array(interp, target, argc-1, argv + 1);
3326 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3328 long l;
3329 uint32_t width;
3330 int len;
3331 uint32_t addr;
3332 uint32_t count;
3333 uint32_t v;
3334 const char *varname;
3335 int n, e, retval;
3336 uint32_t i;
3338 /* argv[1] = name of array to receive the data
3339 * argv[2] = desired width
3340 * argv[3] = memory address
3341 * argv[4] = count of times to read
3343 if (argc != 4) {
3344 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3345 return JIM_ERR;
3347 varname = Jim_GetString(argv[0], &len);
3348 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3350 e = Jim_GetLong(interp, argv[1], &l);
3351 width = l;
3352 if (e != JIM_OK) {
3353 return e;
3356 e = Jim_GetLong(interp, argv[2], &l);
3357 addr = l;
3358 if (e != JIM_OK) {
3359 return e;
3361 e = Jim_GetLong(interp, argv[3], &l);
3362 len = l;
3363 if (e != JIM_OK) {
3364 return e;
3366 switch (width) {
3367 case 8:
3368 width = 1;
3369 break;
3370 case 16:
3371 width = 2;
3372 break;
3373 case 32:
3374 width = 4;
3375 break;
3376 default:
3377 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3378 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3379 return JIM_ERR;
3381 if (len == 0) {
3382 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3383 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3384 return JIM_ERR;
3386 if ((addr + (len * width)) < addr) {
3387 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3388 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3389 return JIM_ERR;
3391 /* absurd transfer size? */
3392 if (len > 65536) {
3393 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3394 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3395 return JIM_ERR;
3398 if ((width == 1) ||
3399 ((width == 2) && ((addr & 1) == 0)) ||
3400 ((width == 4) && ((addr & 3) == 0))) {
3401 /* all is well */
3402 } else {
3403 char buf[100];
3404 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3405 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3406 addr,
3407 width);
3408 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3409 return JIM_ERR;
3412 /* Transfer loop */
3414 /* index counter */
3415 n = 0;
3417 size_t buffersize = 4096;
3418 uint8_t *buffer = malloc(buffersize);
3419 if (buffer == NULL)
3420 return JIM_ERR;
3422 /* assume ok */
3423 e = JIM_OK;
3424 while (len) {
3425 /* Slurp... in buffer size chunks */
3427 count = len; /* in objects.. */
3428 if (count > (buffersize/width)) {
3429 count = (buffersize/width);
3432 retval = target_read_memory(target, addr, width, count, buffer);
3433 if (retval != ERROR_OK) {
3434 /* BOO !*/
3435 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3436 (unsigned int)addr,
3437 (int)width,
3438 (int)count);
3439 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3440 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3441 e = JIM_ERR;
3442 len = 0;
3443 } else {
3444 v = 0; /* shut up gcc */
3445 for (i = 0 ;i < count ;i++, n++) {
3446 switch (width) {
3447 case 4:
3448 v = target_buffer_get_u32(target, &buffer[i*width]);
3449 break;
3450 case 2:
3451 v = target_buffer_get_u16(target, &buffer[i*width]);
3452 break;
3453 case 1:
3454 v = buffer[i] & 0x0ff;
3455 break;
3457 new_int_array_element(interp, varname, n, v);
3459 len -= count;
3463 free(buffer);
3465 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3467 return JIM_OK;
3470 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3472 char *namebuf;
3473 Jim_Obj *nameObjPtr, *valObjPtr;
3474 int result;
3475 long l;
3477 namebuf = alloc_printf("%s(%d)", varname, idx);
3478 if (!namebuf)
3479 return JIM_ERR;
3481 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3482 if (!nameObjPtr)
3484 free(namebuf);
3485 return JIM_ERR;
3488 Jim_IncrRefCount(nameObjPtr);
3489 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3490 Jim_DecrRefCount(interp, nameObjPtr);
3491 free(namebuf);
3492 if (valObjPtr == NULL)
3493 return JIM_ERR;
3495 result = Jim_GetLong(interp, valObjPtr, &l);
3496 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3497 *val = l;
3498 return result;
3501 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3503 struct command_context *context;
3504 struct target *target;
3506 context = current_command_context(interp);
3507 assert (context != NULL);
3509 target = get_current_target(context);
3510 if (target == NULL) {
3511 LOG_ERROR("array2mem: no current target");
3512 return JIM_ERR;
3515 return target_array2mem(interp,target, argc-1, argv + 1);
3518 static int target_array2mem(Jim_Interp *interp, struct target *target,
3519 int argc, Jim_Obj *const *argv)
3521 long l;
3522 uint32_t width;
3523 int len;
3524 uint32_t addr;
3525 uint32_t count;
3526 uint32_t v;
3527 const char *varname;
3528 int n, e, retval;
3529 uint32_t i;
3531 /* argv[1] = name of array to get the data
3532 * argv[2] = desired width
3533 * argv[3] = memory address
3534 * argv[4] = count to write
3536 if (argc != 4) {
3537 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3538 return JIM_ERR;
3540 varname = Jim_GetString(argv[0], &len);
3541 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3543 e = Jim_GetLong(interp, argv[1], &l);
3544 width = l;
3545 if (e != JIM_OK) {
3546 return e;
3549 e = Jim_GetLong(interp, argv[2], &l);
3550 addr = l;
3551 if (e != JIM_OK) {
3552 return e;
3554 e = Jim_GetLong(interp, argv[3], &l);
3555 len = l;
3556 if (e != JIM_OK) {
3557 return e;
3559 switch (width) {
3560 case 8:
3561 width = 1;
3562 break;
3563 case 16:
3564 width = 2;
3565 break;
3566 case 32:
3567 width = 4;
3568 break;
3569 default:
3570 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3571 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3572 return JIM_ERR;
3574 if (len == 0) {
3575 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3576 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3577 return JIM_ERR;
3579 if ((addr + (len * width)) < addr) {
3580 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3581 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3582 return JIM_ERR;
3584 /* absurd transfer size? */
3585 if (len > 65536) {
3586 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3587 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3588 return JIM_ERR;
3591 if ((width == 1) ||
3592 ((width == 2) && ((addr & 1) == 0)) ||
3593 ((width == 4) && ((addr & 3) == 0))) {
3594 /* all is well */
3595 } else {
3596 char buf[100];
3597 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3598 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3599 (unsigned int)addr,
3600 (int)width);
3601 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3602 return JIM_ERR;
3605 /* Transfer loop */
3607 /* index counter */
3608 n = 0;
3609 /* assume ok */
3610 e = JIM_OK;
3612 size_t buffersize = 4096;
3613 uint8_t *buffer = malloc(buffersize);
3614 if (buffer == NULL)
3615 return JIM_ERR;
3617 while (len) {
3618 /* Slurp... in buffer size chunks */
3620 count = len; /* in objects.. */
3621 if (count > (buffersize/width)) {
3622 count = (buffersize/width);
3625 v = 0; /* shut up gcc */
3626 for (i = 0 ;i < count ;i++, n++) {
3627 get_int_array_element(interp, varname, n, &v);
3628 switch (width) {
3629 case 4:
3630 target_buffer_set_u32(target, &buffer[i*width], v);
3631 break;
3632 case 2:
3633 target_buffer_set_u16(target, &buffer[i*width], v);
3634 break;
3635 case 1:
3636 buffer[i] = v & 0x0ff;
3637 break;
3640 len -= count;
3642 retval = target_write_memory(target, addr, width, count, buffer);
3643 if (retval != ERROR_OK) {
3644 /* BOO !*/
3645 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3646 (unsigned int)addr,
3647 (int)width,
3648 (int)count);
3649 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3650 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3651 e = JIM_ERR;
3652 len = 0;
3656 free(buffer);
3658 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3660 return JIM_OK;
3663 /* FIX? should we propagate errors here rather than printing them
3664 * and continuing?
3666 void target_handle_event(struct target *target, enum target_event e)
3668 struct target_event_action *teap;
3670 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3671 if (teap->event == e) {
3672 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3673 target->target_number,
3674 target_name(target),
3675 target_type_name(target),
3677 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3678 Jim_GetString(teap->body, NULL));
3679 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3681 Jim_MakeErrorMessage(teap->interp);
3682 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3689 * Returns true only if the target has a handler for the specified event.
3691 bool target_has_event_action(struct target *target, enum target_event event)
3693 struct target_event_action *teap;
3695 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3696 if (teap->event == event)
3697 return true;
3699 return false;
3702 enum target_cfg_param {
3703 TCFG_TYPE,
3704 TCFG_EVENT,
3705 TCFG_WORK_AREA_VIRT,
3706 TCFG_WORK_AREA_PHYS,
3707 TCFG_WORK_AREA_SIZE,
3708 TCFG_WORK_AREA_BACKUP,
3709 TCFG_ENDIAN,
3710 TCFG_VARIANT,
3711 TCFG_COREID,
3712 TCFG_CHAIN_POSITION,
3713 TCFG_DBGBASE,
3714 TCFG_RTOS,
3717 static Jim_Nvp nvp_config_opts[] = {
3718 { .name = "-type", .value = TCFG_TYPE },
3719 { .name = "-event", .value = TCFG_EVENT },
3720 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3721 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3722 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3723 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3724 { .name = "-endian" , .value = TCFG_ENDIAN },
3725 { .name = "-variant", .value = TCFG_VARIANT },
3726 { .name = "-coreid", .value = TCFG_COREID },
3727 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3728 { .name = "-dbgbase", .value = TCFG_DBGBASE },
3729 { .name = "-rtos", .value = TCFG_RTOS },
3730 { .name = NULL, .value = -1 }
3733 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3735 Jim_Nvp *n;
3736 Jim_Obj *o;
3737 jim_wide w;
3738 char *cp;
3739 int e;
3741 /* parse config or cget options ... */
3742 while (goi->argc > 0) {
3743 Jim_SetEmptyResult(goi->interp);
3744 /* Jim_GetOpt_Debug(goi); */
3746 if (target->type->target_jim_configure) {
3747 /* target defines a configure function */
3748 /* target gets first dibs on parameters */
3749 e = (*(target->type->target_jim_configure))(target, goi);
3750 if (e == JIM_OK) {
3751 /* more? */
3752 continue;
3754 if (e == JIM_ERR) {
3755 /* An error */
3756 return e;
3758 /* otherwise we 'continue' below */
3760 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3761 if (e != JIM_OK) {
3762 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3763 return e;
3765 switch (n->value) {
3766 case TCFG_TYPE:
3767 /* not setable */
3768 if (goi->isconfigure) {
3769 Jim_SetResultFormatted(goi->interp,
3770 "not settable: %s", n->name);
3771 return JIM_ERR;
3772 } else {
3773 no_params:
3774 if (goi->argc != 0) {
3775 Jim_WrongNumArgs(goi->interp,
3776 goi->argc, goi->argv,
3777 "NO PARAMS");
3778 return JIM_ERR;
3781 Jim_SetResultString(goi->interp,
3782 target_type_name(target), -1);
3783 /* loop for more */
3784 break;
3785 case TCFG_EVENT:
3786 if (goi->argc == 0) {
3787 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3788 return JIM_ERR;
3791 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3792 if (e != JIM_OK) {
3793 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3794 return e;
3797 if (goi->isconfigure) {
3798 if (goi->argc != 1) {
3799 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3800 return JIM_ERR;
3802 } else {
3803 if (goi->argc != 0) {
3804 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3805 return JIM_ERR;
3810 struct target_event_action *teap;
3812 teap = target->event_action;
3813 /* replace existing? */
3814 while (teap) {
3815 if (teap->event == (enum target_event)n->value) {
3816 break;
3818 teap = teap->next;
3821 if (goi->isconfigure) {
3822 bool replace = true;
3823 if (teap == NULL) {
3824 /* create new */
3825 teap = calloc(1, sizeof(*teap));
3826 replace = false;
3828 teap->event = n->value;
3829 teap->interp = goi->interp;
3830 Jim_GetOpt_Obj(goi, &o);
3831 if (teap->body) {
3832 Jim_DecrRefCount(teap->interp, teap->body);
3834 teap->body = Jim_DuplicateObj(goi->interp, o);
3836 * FIXME:
3837 * Tcl/TK - "tk events" have a nice feature.
3838 * See the "BIND" command.
3839 * We should support that here.
3840 * You can specify %X and %Y in the event code.
3841 * The idea is: %T - target name.
3842 * The idea is: %N - target number
3843 * The idea is: %E - event name.
3845 Jim_IncrRefCount(teap->body);
3847 if (!replace)
3849 /* add to head of event list */
3850 teap->next = target->event_action;
3851 target->event_action = teap;
3853 Jim_SetEmptyResult(goi->interp);
3854 } else {
3855 /* get */
3856 if (teap == NULL) {
3857 Jim_SetEmptyResult(goi->interp);
3858 } else {
3859 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3863 /* loop for more */
3864 break;
3866 case TCFG_WORK_AREA_VIRT:
3867 if (goi->isconfigure) {
3868 target_free_all_working_areas(target);
3869 e = Jim_GetOpt_Wide(goi, &w);
3870 if (e != JIM_OK) {
3871 return e;
3873 target->working_area_virt = w;
3874 target->working_area_virt_spec = true;
3875 } else {
3876 if (goi->argc != 0) {
3877 goto no_params;
3880 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3881 /* loop for more */
3882 break;
3884 case TCFG_WORK_AREA_PHYS:
3885 if (goi->isconfigure) {
3886 target_free_all_working_areas(target);
3887 e = Jim_GetOpt_Wide(goi, &w);
3888 if (e != JIM_OK) {
3889 return e;
3891 target->working_area_phys = w;
3892 target->working_area_phys_spec = true;
3893 } else {
3894 if (goi->argc != 0) {
3895 goto no_params;
3898 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3899 /* loop for more */
3900 break;
3902 case TCFG_WORK_AREA_SIZE:
3903 if (goi->isconfigure) {
3904 target_free_all_working_areas(target);
3905 e = Jim_GetOpt_Wide(goi, &w);
3906 if (e != JIM_OK) {
3907 return e;
3909 target->working_area_size = w;
3910 } else {
3911 if (goi->argc != 0) {
3912 goto no_params;
3915 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3916 /* loop for more */
3917 break;
3919 case TCFG_WORK_AREA_BACKUP:
3920 if (goi->isconfigure) {
3921 target_free_all_working_areas(target);
3922 e = Jim_GetOpt_Wide(goi, &w);
3923 if (e != JIM_OK) {
3924 return e;
3926 /* make this exactly 1 or 0 */
3927 target->backup_working_area = (!!w);
3928 } else {
3929 if (goi->argc != 0) {
3930 goto no_params;
3933 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3934 /* loop for more e*/
3935 break;
3938 case TCFG_ENDIAN:
3939 if (goi->isconfigure) {
3940 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3941 if (e != JIM_OK) {
3942 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3943 return e;
3945 target->endianness = n->value;
3946 } else {
3947 if (goi->argc != 0) {
3948 goto no_params;
3951 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3952 if (n->name == NULL) {
3953 target->endianness = TARGET_LITTLE_ENDIAN;
3954 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3956 Jim_SetResultString(goi->interp, n->name, -1);
3957 /* loop for more */
3958 break;
3960 case TCFG_VARIANT:
3961 if (goi->isconfigure) {
3962 if (goi->argc < 1) {
3963 Jim_SetResultFormatted(goi->interp,
3964 "%s ?STRING?",
3965 n->name);
3966 return JIM_ERR;
3968 if (target->variant) {
3969 free((void *)(target->variant));
3971 e = Jim_GetOpt_String(goi, &cp, NULL);
3972 target->variant = strdup(cp);
3973 } else {
3974 if (goi->argc != 0) {
3975 goto no_params;
3978 Jim_SetResultString(goi->interp, target->variant,-1);
3979 /* loop for more */
3980 break;
3982 case TCFG_COREID:
3983 if (goi->isconfigure) {
3984 e = Jim_GetOpt_Wide(goi, &w);
3985 if (e != JIM_OK) {
3986 return e;
3988 target->coreid = (int32_t)w;
3989 } else {
3990 if (goi->argc != 0) {
3991 goto no_params;
3994 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3995 /* loop for more */
3996 break;
3998 case TCFG_CHAIN_POSITION:
3999 if (goi->isconfigure) {
4000 Jim_Obj *o_t;
4001 struct jtag_tap *tap;
4002 target_free_all_working_areas(target);
4003 e = Jim_GetOpt_Obj(goi, &o_t);
4004 if (e != JIM_OK) {
4005 return e;
4007 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4008 if (tap == NULL) {
4009 return JIM_ERR;
4011 /* make this exactly 1 or 0 */
4012 target->tap = tap;
4013 } else {
4014 if (goi->argc != 0) {
4015 goto no_params;
4018 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4019 /* loop for more e*/
4020 break;
4021 case TCFG_DBGBASE:
4022 if (goi->isconfigure) {
4023 e = Jim_GetOpt_Wide(goi, &w);
4024 if (e != JIM_OK) {
4025 return e;
4027 target->dbgbase = (uint32_t)w;
4028 target->dbgbase_set = true;
4029 } else {
4030 if (goi->argc != 0) {
4031 goto no_params;
4034 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4035 /* loop for more */
4036 break;
4038 case TCFG_RTOS:
4039 /* RTOS */
4041 int result = rtos_create( goi, target );
4042 if ( result != JIM_OK )
4044 return result;
4047 /* loop for more */
4048 break;
4050 } /* while (goi->argc) */
4053 /* done - we return */
4054 return JIM_OK;
4057 static int
4058 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4060 Jim_GetOptInfo goi;
4062 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4063 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4064 int need_args = 1 + goi.isconfigure;
4065 if (goi.argc < need_args)
4067 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4068 goi.isconfigure
4069 ? "missing: -option VALUE ..."
4070 : "missing: -option ...");
4071 return JIM_ERR;
4073 struct target *target = Jim_CmdPrivData(goi.interp);
4074 return target_configure(&goi, target);
4077 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4079 const char *cmd_name = Jim_GetString(argv[0], NULL);
4081 Jim_GetOptInfo goi;
4082 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4084 if (goi.argc < 2 || goi.argc > 4)
4086 Jim_SetResultFormatted(goi.interp,
4087 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4088 return JIM_ERR;
4091 target_write_fn fn;
4092 fn = target_write_memory_fast;
4094 int e;
4095 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4097 /* consume it */
4098 struct Jim_Obj *obj;
4099 e = Jim_GetOpt_Obj(&goi, &obj);
4100 if (e != JIM_OK)
4101 return e;
4103 fn = target_write_phys_memory;
4106 jim_wide a;
4107 e = Jim_GetOpt_Wide(&goi, &a);
4108 if (e != JIM_OK)
4109 return e;
4111 jim_wide b;
4112 e = Jim_GetOpt_Wide(&goi, &b);
4113 if (e != JIM_OK)
4114 return e;
4116 jim_wide c = 1;
4117 if (goi.argc == 1)
4119 e = Jim_GetOpt_Wide(&goi, &c);
4120 if (e != JIM_OK)
4121 return e;
4124 /* all args must be consumed */
4125 if (goi.argc != 0)
4127 return JIM_ERR;
4130 struct target *target = Jim_CmdPrivData(goi.interp);
4131 unsigned data_size;
4132 if (strcasecmp(cmd_name, "mww") == 0) {
4133 data_size = 4;
4135 else if (strcasecmp(cmd_name, "mwh") == 0) {
4136 data_size = 2;
4138 else if (strcasecmp(cmd_name, "mwb") == 0) {
4139 data_size = 1;
4140 } else {
4141 LOG_ERROR("command '%s' unknown: ", cmd_name);
4142 return JIM_ERR;
4145 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4148 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4150 const char *cmd_name = Jim_GetString(argv[0], NULL);
4152 Jim_GetOptInfo goi;
4153 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4155 if ((goi.argc < 1) || (goi.argc > 3))
4157 Jim_SetResultFormatted(goi.interp,
4158 "usage: %s [phys] <address> [<count>]", cmd_name);
4159 return JIM_ERR;
4162 int (*fn)(struct target *target,
4163 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4164 fn=target_read_memory;
4166 int e;
4167 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4169 /* consume it */
4170 struct Jim_Obj *obj;
4171 e = Jim_GetOpt_Obj(&goi, &obj);
4172 if (e != JIM_OK)
4173 return e;
4175 fn=target_read_phys_memory;
4178 jim_wide a;
4179 e = Jim_GetOpt_Wide(&goi, &a);
4180 if (e != JIM_OK) {
4181 return JIM_ERR;
4183 jim_wide c;
4184 if (goi.argc == 1) {
4185 e = Jim_GetOpt_Wide(&goi, &c);
4186 if (e != JIM_OK) {
4187 return JIM_ERR;
4189 } else {
4190 c = 1;
4193 /* all args must be consumed */
4194 if (goi.argc != 0)
4196 return JIM_ERR;
4199 jim_wide b = 1; /* shut up gcc */
4200 if (strcasecmp(cmd_name, "mdw") == 0)
4201 b = 4;
4202 else if (strcasecmp(cmd_name, "mdh") == 0)
4203 b = 2;
4204 else if (strcasecmp(cmd_name, "mdb") == 0)
4205 b = 1;
4206 else {
4207 LOG_ERROR("command '%s' unknown: ", cmd_name);
4208 return JIM_ERR;
4211 /* convert count to "bytes" */
4212 c = c * b;
4214 struct target *target = Jim_CmdPrivData(goi.interp);
4215 uint8_t target_buf[32];
4216 jim_wide x, y, z;
4217 while (c > 0) {
4218 y = c;
4219 if (y > 16) {
4220 y = 16;
4222 e = fn(target, a, b, y / b, target_buf);
4223 if (e != ERROR_OK) {
4224 char tmp[10];
4225 snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4226 Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4227 return JIM_ERR;
4230 command_print(NULL, "0x%08x ", (int)(a));
4231 switch (b) {
4232 case 4:
4233 for (x = 0; x < 16 && x < y; x += 4)
4235 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4236 command_print(NULL, "%08x ", (int)(z));
4238 for (; (x < 16) ; x += 4) {
4239 command_print(NULL, " ");
4241 break;
4242 case 2:
4243 for (x = 0; x < 16 && x < y; x += 2)
4245 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4246 command_print(NULL, "%04x ", (int)(z));
4248 for (; (x < 16) ; x += 2) {
4249 command_print(NULL, " ");
4251 break;
4252 case 1:
4253 default:
4254 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4255 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4256 command_print(NULL, "%02x ", (int)(z));
4258 for (; (x < 16) ; x += 1) {
4259 command_print(NULL, " ");
4261 break;
4263 /* ascii-ify the bytes */
4264 for (x = 0 ; x < y ; x++) {
4265 if ((target_buf[x] >= 0x20) &&
4266 (target_buf[x] <= 0x7e)) {
4267 /* good */
4268 } else {
4269 /* smack it */
4270 target_buf[x] = '.';
4273 /* space pad */
4274 while (x < 16) {
4275 target_buf[x] = ' ';
4276 x++;
4278 /* terminate */
4279 target_buf[16] = 0;
4280 /* print - with a newline */
4281 command_print(NULL, "%s\n", target_buf);
4282 /* NEXT... */
4283 c -= 16;
4284 a += 16;
4286 return JIM_OK;
4289 static int jim_target_mem2array(Jim_Interp *interp,
4290 int argc, Jim_Obj *const *argv)
4292 struct target *target = Jim_CmdPrivData(interp);
4293 return target_mem2array(interp, target, argc - 1, argv + 1);
4296 static int jim_target_array2mem(Jim_Interp *interp,
4297 int argc, Jim_Obj *const *argv)
4299 struct target *target = Jim_CmdPrivData(interp);
4300 return target_array2mem(interp, target, argc - 1, argv + 1);
4303 static int jim_target_tap_disabled(Jim_Interp *interp)
4305 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4306 return JIM_ERR;
4309 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4311 if (argc != 1)
4313 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4314 return JIM_ERR;
4316 struct target *target = Jim_CmdPrivData(interp);
4317 if (!target->tap->enabled)
4318 return jim_target_tap_disabled(interp);
4320 int e = target->type->examine(target);
4321 if (e != ERROR_OK)
4323 return JIM_ERR;
4325 return JIM_OK;
4328 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4330 if (argc != 1)
4332 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4333 return JIM_ERR;
4335 struct target *target = Jim_CmdPrivData(interp);
4337 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4338 return JIM_ERR;
4340 return JIM_OK;
4343 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4345 if (argc != 1)
4347 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4348 return JIM_ERR;
4350 struct target *target = Jim_CmdPrivData(interp);
4351 if (!target->tap->enabled)
4352 return jim_target_tap_disabled(interp);
4354 int e;
4355 if (!(target_was_examined(target))) {
4356 e = ERROR_TARGET_NOT_EXAMINED;
4357 } else {
4358 e = target->type->poll(target);
4360 if (e != ERROR_OK)
4362 return JIM_ERR;
4364 return JIM_OK;
4367 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4369 Jim_GetOptInfo goi;
4370 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4372 if (goi.argc != 2)
4374 Jim_WrongNumArgs(interp, 0, argv,
4375 "([tT]|[fF]|assert|deassert) BOOL");
4376 return JIM_ERR;
4379 Jim_Nvp *n;
4380 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4381 if (e != JIM_OK)
4383 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4384 return e;
4386 /* the halt or not param */
4387 jim_wide a;
4388 e = Jim_GetOpt_Wide(&goi, &a);
4389 if (e != JIM_OK)
4390 return e;
4392 struct target *target = Jim_CmdPrivData(goi.interp);
4393 if (!target->tap->enabled)
4394 return jim_target_tap_disabled(interp);
4395 if (!(target_was_examined(target)))
4397 LOG_ERROR("Target not examined yet");
4398 return ERROR_TARGET_NOT_EXAMINED;
4400 if (!target->type->assert_reset || !target->type->deassert_reset)
4402 Jim_SetResultFormatted(interp,
4403 "No target-specific reset for %s",
4404 target_name(target));
4405 return JIM_ERR;
4407 /* determine if we should halt or not. */
4408 target->reset_halt = !!a;
4409 /* When this happens - all workareas are invalid. */
4410 target_free_all_working_areas_restore(target, 0);
4412 /* do the assert */
4413 if (n->value == NVP_ASSERT) {
4414 e = target->type->assert_reset(target);
4415 } else {
4416 e = target->type->deassert_reset(target);
4418 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4421 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4423 if (argc != 1) {
4424 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4425 return JIM_ERR;
4427 struct target *target = Jim_CmdPrivData(interp);
4428 if (!target->tap->enabled)
4429 return jim_target_tap_disabled(interp);
4430 int e = target->type->halt(target);
4431 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4434 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4436 Jim_GetOptInfo goi;
4437 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4439 /* params: <name> statename timeoutmsecs */
4440 if (goi.argc != 2)
4442 const char *cmd_name = Jim_GetString(argv[0], NULL);
4443 Jim_SetResultFormatted(goi.interp,
4444 "%s <state_name> <timeout_in_msec>", cmd_name);
4445 return JIM_ERR;
4448 Jim_Nvp *n;
4449 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4450 if (e != JIM_OK) {
4451 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4452 return e;
4454 jim_wide a;
4455 e = Jim_GetOpt_Wide(&goi, &a);
4456 if (e != JIM_OK) {
4457 return e;
4459 struct target *target = Jim_CmdPrivData(interp);
4460 if (!target->tap->enabled)
4461 return jim_target_tap_disabled(interp);
4463 e = target_wait_state(target, n->value, a);
4464 if (e != ERROR_OK)
4466 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4467 Jim_SetResultFormatted(goi.interp,
4468 "target: %s wait %s fails (%#s) %s",
4469 target_name(target), n->name,
4470 eObj, target_strerror_safe(e));
4471 Jim_FreeNewObj(interp, eObj);
4472 return JIM_ERR;
4474 return JIM_OK;
4476 /* List for human, Events defined for this target.
4477 * scripts/programs should use 'name cget -event NAME'
4479 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4481 struct command_context *cmd_ctx = current_command_context(interp);
4482 assert (cmd_ctx != NULL);
4484 struct target *target = Jim_CmdPrivData(interp);
4485 struct target_event_action *teap = target->event_action;
4486 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4487 target->target_number,
4488 target_name(target));
4489 command_print(cmd_ctx, "%-25s | Body", "Event");
4490 command_print(cmd_ctx, "------------------------- | "
4491 "----------------------------------------");
4492 while (teap)
4494 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4495 command_print(cmd_ctx, "%-25s | %s",
4496 opt->name, Jim_GetString(teap->body, NULL));
4497 teap = teap->next;
4499 command_print(cmd_ctx, "***END***");
4500 return JIM_OK;
4502 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4504 if (argc != 1)
4506 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4507 return JIM_ERR;
4509 struct target *target = Jim_CmdPrivData(interp);
4510 Jim_SetResultString(interp, target_state_name(target), -1);
4511 return JIM_OK;
4513 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4515 Jim_GetOptInfo goi;
4516 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4517 if (goi.argc != 1)
4519 const char *cmd_name = Jim_GetString(argv[0], NULL);
4520 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4521 return JIM_ERR;
4523 Jim_Nvp *n;
4524 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4525 if (e != JIM_OK)
4527 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4528 return e;
4530 struct target *target = Jim_CmdPrivData(interp);
4531 target_handle_event(target, n->value);
4532 return JIM_OK;
4535 static const struct command_registration target_instance_command_handlers[] = {
4537 .name = "configure",
4538 .mode = COMMAND_CONFIG,
4539 .jim_handler = jim_target_configure,
4540 .help = "configure a new target for use",
4541 .usage = "[target_attribute ...]",
4544 .name = "cget",
4545 .mode = COMMAND_ANY,
4546 .jim_handler = jim_target_configure,
4547 .help = "returns the specified target attribute",
4548 .usage = "target_attribute",
4551 .name = "mww",
4552 .mode = COMMAND_EXEC,
4553 .jim_handler = jim_target_mw,
4554 .help = "Write 32-bit word(s) to target memory",
4555 .usage = "address data [count]",
4558 .name = "mwh",
4559 .mode = COMMAND_EXEC,
4560 .jim_handler = jim_target_mw,
4561 .help = "Write 16-bit half-word(s) to target memory",
4562 .usage = "address data [count]",
4565 .name = "mwb",
4566 .mode = COMMAND_EXEC,
4567 .jim_handler = jim_target_mw,
4568 .help = "Write byte(s) to target memory",
4569 .usage = "address data [count]",
4572 .name = "mdw",
4573 .mode = COMMAND_EXEC,
4574 .jim_handler = jim_target_md,
4575 .help = "Display target memory as 32-bit words",
4576 .usage = "address [count]",
4579 .name = "mdh",
4580 .mode = COMMAND_EXEC,
4581 .jim_handler = jim_target_md,
4582 .help = "Display target memory as 16-bit half-words",
4583 .usage = "address [count]",
4586 .name = "mdb",
4587 .mode = COMMAND_EXEC,
4588 .jim_handler = jim_target_md,
4589 .help = "Display target memory as 8-bit bytes",
4590 .usage = "address [count]",
4593 .name = "array2mem",
4594 .mode = COMMAND_EXEC,
4595 .jim_handler = jim_target_array2mem,
4596 .help = "Writes Tcl array of 8/16/32 bit numbers "
4597 "to target memory",
4598 .usage = "arrayname bitwidth address count",
4601 .name = "mem2array",
4602 .mode = COMMAND_EXEC,
4603 .jim_handler = jim_target_mem2array,
4604 .help = "Loads Tcl array of 8/16/32 bit numbers "
4605 "from target memory",
4606 .usage = "arrayname bitwidth address count",
4609 .name = "eventlist",
4610 .mode = COMMAND_EXEC,
4611 .jim_handler = jim_target_event_list,
4612 .help = "displays a table of events defined for this target",
4615 .name = "curstate",
4616 .mode = COMMAND_EXEC,
4617 .jim_handler = jim_target_current_state,
4618 .help = "displays the current state of this target",
4621 .name = "arp_examine",
4622 .mode = COMMAND_EXEC,
4623 .jim_handler = jim_target_examine,
4624 .help = "used internally for reset processing",
4627 .name = "arp_halt_gdb",
4628 .mode = COMMAND_EXEC,
4629 .jim_handler = jim_target_halt_gdb,
4630 .help = "used internally for reset processing to halt GDB",
4633 .name = "arp_poll",
4634 .mode = COMMAND_EXEC,
4635 .jim_handler = jim_target_poll,
4636 .help = "used internally for reset processing",
4639 .name = "arp_reset",
4640 .mode = COMMAND_EXEC,
4641 .jim_handler = jim_target_reset,
4642 .help = "used internally for reset processing",
4645 .name = "arp_halt",
4646 .mode = COMMAND_EXEC,
4647 .jim_handler = jim_target_halt,
4648 .help = "used internally for reset processing",
4651 .name = "arp_waitstate",
4652 .mode = COMMAND_EXEC,
4653 .jim_handler = jim_target_wait_state,
4654 .help = "used internally for reset processing",
4657 .name = "invoke-event",
4658 .mode = COMMAND_EXEC,
4659 .jim_handler = jim_target_invoke_event,
4660 .help = "invoke handler for specified event",
4661 .usage = "event_name",
4663 COMMAND_REGISTRATION_DONE
4666 static int target_create(Jim_GetOptInfo *goi)
4668 Jim_Obj *new_cmd;
4669 Jim_Cmd *cmd;
4670 const char *cp;
4671 char *cp2;
4672 int e;
4673 int x;
4674 struct target *target;
4675 struct command_context *cmd_ctx;
4677 cmd_ctx = current_command_context(goi->interp);
4678 assert (cmd_ctx != NULL);
4680 if (goi->argc < 3) {
4681 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4682 return JIM_ERR;
4685 /* COMMAND */
4686 Jim_GetOpt_Obj(goi, &new_cmd);
4687 /* does this command exist? */
4688 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4689 if (cmd) {
4690 cp = Jim_GetString(new_cmd, NULL);
4691 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4692 return JIM_ERR;
4695 /* TYPE */
4696 e = Jim_GetOpt_String(goi, &cp2, NULL);
4697 cp = cp2;
4698 /* now does target type exist */
4699 for (x = 0 ; target_types[x] ; x++) {
4700 if (0 == strcmp(cp, target_types[x]->name)) {
4701 /* found */
4702 break;
4705 if (target_types[x] == NULL) {
4706 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4707 for (x = 0 ; target_types[x] ; x++) {
4708 if (target_types[x + 1]) {
4709 Jim_AppendStrings(goi->interp,
4710 Jim_GetResult(goi->interp),
4711 target_types[x]->name,
4712 ", ", NULL);
4713 } else {
4714 Jim_AppendStrings(goi->interp,
4715 Jim_GetResult(goi->interp),
4716 " or ",
4717 target_types[x]->name,NULL);
4720 return JIM_ERR;
4723 /* Create it */
4724 target = calloc(1,sizeof(struct target));
4725 /* set target number */
4726 target->target_number = new_target_number();
4728 /* allocate memory for each unique target type */
4729 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4731 memcpy(target->type, target_types[x], sizeof(struct target_type));
4733 /* will be set by "-endian" */
4734 target->endianness = TARGET_ENDIAN_UNKNOWN;
4736 /* default to first core, override with -coreid */
4737 target->coreid = 0;
4739 target->working_area = 0x0;
4740 target->working_area_size = 0x0;
4741 target->working_areas = NULL;
4742 target->backup_working_area = 0;
4744 target->state = TARGET_UNKNOWN;
4745 target->debug_reason = DBG_REASON_UNDEFINED;
4746 target->reg_cache = NULL;
4747 target->breakpoints = NULL;
4748 target->watchpoints = NULL;
4749 target->next = NULL;
4750 target->arch_info = NULL;
4752 target->display = 1;
4754 target->halt_issued = false;
4756 /* initialize trace information */
4757 target->trace_info = malloc(sizeof(struct trace));
4758 target->trace_info->num_trace_points = 0;
4759 target->trace_info->trace_points_size = 0;
4760 target->trace_info->trace_points = NULL;
4761 target->trace_info->trace_history_size = 0;
4762 target->trace_info->trace_history = NULL;
4763 target->trace_info->trace_history_pos = 0;
4764 target->trace_info->trace_history_overflowed = 0;
4766 target->dbgmsg = NULL;
4767 target->dbg_msg_enabled = 0;
4769 target->endianness = TARGET_ENDIAN_UNKNOWN;
4771 target->rtos = NULL;
4772 target->rtos_auto_detect = false;
4774 /* Do the rest as "configure" options */
4775 goi->isconfigure = 1;
4776 e = target_configure(goi, target);
4778 if (target->tap == NULL)
4780 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4781 e = JIM_ERR;
4784 if (e != JIM_OK) {
4785 free(target->type);
4786 free(target);
4787 return e;
4790 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4791 /* default endian to little if not specified */
4792 target->endianness = TARGET_LITTLE_ENDIAN;
4795 /* incase variant is not set */
4796 if (!target->variant)
4797 target->variant = strdup("");
4799 cp = Jim_GetString(new_cmd, NULL);
4800 target->cmd_name = strdup(cp);
4802 /* create the target specific commands */
4803 if (target->type->commands) {
4804 e = register_commands(cmd_ctx, NULL, target->type->commands);
4805 if (ERROR_OK != e)
4806 LOG_ERROR("unable to register '%s' commands", cp);
4808 if (target->type->target_create) {
4809 (*(target->type->target_create))(target, goi->interp);
4812 /* append to end of list */
4814 struct target **tpp;
4815 tpp = &(all_targets);
4816 while (*tpp) {
4817 tpp = &((*tpp)->next);
4819 *tpp = target;
4822 /* now - create the new target name command */
4823 const const struct command_registration target_subcommands[] = {
4825 .chain = target_instance_command_handlers,
4828 .chain = target->type->commands,
4830 COMMAND_REGISTRATION_DONE
4832 const const struct command_registration target_commands[] = {
4834 .name = cp,
4835 .mode = COMMAND_ANY,
4836 .help = "target command group",
4837 .chain = target_subcommands,
4839 COMMAND_REGISTRATION_DONE
4841 e = register_commands(cmd_ctx, NULL, target_commands);
4842 if (ERROR_OK != e)
4843 return JIM_ERR;
4845 struct command *c = command_find_in_context(cmd_ctx, cp);
4846 assert(c);
4847 command_set_handler_data(c, target);
4849 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4852 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4854 if (argc != 1)
4856 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4857 return JIM_ERR;
4859 struct command_context *cmd_ctx = current_command_context(interp);
4860 assert (cmd_ctx != NULL);
4862 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4863 return JIM_OK;
4866 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4868 if (argc != 1)
4870 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4871 return JIM_ERR;
4873 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4874 for (unsigned x = 0; NULL != target_types[x]; x++)
4876 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4877 Jim_NewStringObj(interp, target_types[x]->name, -1));
4879 return JIM_OK;
4882 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4884 if (argc != 1)
4886 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4887 return JIM_ERR;
4889 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4890 struct target *target = all_targets;
4891 while (target)
4893 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4894 Jim_NewStringObj(interp, target_name(target), -1));
4895 target = target->next;
4897 return JIM_OK;
4900 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4902 int i;
4903 const char *targetname;
4904 int retval,len;
4905 struct target *target;
4906 struct target_list *head, *curr, *new;
4907 curr = (struct target_list*) NULL;
4908 head = (struct target_list*) NULL;
4909 new = (struct target_list*) NULL;
4911 retval = 0;
4912 LOG_DEBUG("%d",argc);
4913 /* argv[1] = target to associate in smp
4914 * argv[2] = target to assoicate in smp
4915 * argv[3] ...
4918 for(i=1;i<argc;i++)
4921 targetname = Jim_GetString(argv[i], &len);
4922 target = get_target(targetname);
4923 LOG_DEBUG("%s ",targetname);
4924 if (target)
4926 new=malloc(sizeof(struct target_list));
4927 new->target = target;
4928 new->next = (struct target_list*)NULL;
4929 if (head == (struct target_list*)NULL)
4931 head = new;
4932 curr = head;
4934 else
4936 curr->next = new;
4937 curr = new;
4941 /* now parse the list of cpu and put the target in smp mode*/
4942 curr=head;
4944 while(curr!=(struct target_list *)NULL)
4946 target=curr->target;
4947 target->smp = 1;
4948 target->head = head;
4949 curr=curr->next;
4951 return retval;
4955 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4957 Jim_GetOptInfo goi;
4958 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4959 if (goi.argc < 3)
4961 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4962 "<name> <target_type> [<target_options> ...]");
4963 return JIM_ERR;
4965 return target_create(&goi);
4968 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4970 Jim_GetOptInfo goi;
4971 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4973 /* It's OK to remove this mechanism sometime after August 2010 or so */
4974 LOG_WARNING("don't use numbers as target identifiers; use names");
4975 if (goi.argc != 1)
4977 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
4978 return JIM_ERR;
4980 jim_wide w;
4981 int e = Jim_GetOpt_Wide(&goi, &w);
4982 if (e != JIM_OK)
4983 return JIM_ERR;
4985 struct target *target;
4986 for (target = all_targets; NULL != target; target = target->next)
4988 if (target->target_number != w)
4989 continue;
4991 Jim_SetResultString(goi.interp, target_name(target), -1);
4992 return JIM_OK;
4995 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
4996 Jim_SetResultFormatted(goi.interp,
4997 "Target: number %#s does not exist", wObj);
4998 Jim_FreeNewObj(interp, wObj);
5000 return JIM_ERR;
5003 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5005 if (argc != 1)
5007 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5008 return JIM_ERR;
5010 unsigned count = 0;
5011 struct target *target = all_targets;
5012 while (NULL != target)
5014 target = target->next;
5015 count++;
5017 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5018 return JIM_OK;
5021 static const struct command_registration target_subcommand_handlers[] = {
5023 .name = "init",
5024 .mode = COMMAND_CONFIG,
5025 .handler = handle_target_init_command,
5026 .help = "initialize targets",
5029 .name = "create",
5030 /* REVISIT this should be COMMAND_CONFIG ... */
5031 .mode = COMMAND_ANY,
5032 .jim_handler = jim_target_create,
5033 .usage = "name type '-chain-position' name [options ...]",
5034 .help = "Creates and selects a new target",
5037 .name = "current",
5038 .mode = COMMAND_ANY,
5039 .jim_handler = jim_target_current,
5040 .help = "Returns the currently selected target",
5043 .name = "types",
5044 .mode = COMMAND_ANY,
5045 .jim_handler = jim_target_types,
5046 .help = "Returns the available target types as "
5047 "a list of strings",
5050 .name = "names",
5051 .mode = COMMAND_ANY,
5052 .jim_handler = jim_target_names,
5053 .help = "Returns the names of all targets as a list of strings",
5056 .name = "number",
5057 .mode = COMMAND_ANY,
5058 .jim_handler = jim_target_number,
5059 .usage = "number",
5060 .help = "Returns the name of the numbered target "
5061 "(DEPRECATED)",
5064 .name = "count",
5065 .mode = COMMAND_ANY,
5066 .jim_handler = jim_target_count,
5067 .help = "Returns the number of targets as an integer "
5068 "(DEPRECATED)",
5071 .name = "smp",
5072 .mode = COMMAND_ANY,
5073 .jim_handler = jim_target_smp,
5074 .usage = "targetname1 targetname2 ...",
5075 .help = "gather several target in a smp list"
5078 COMMAND_REGISTRATION_DONE
5081 struct FastLoad
5083 uint32_t address;
5084 uint8_t *data;
5085 int length;
5089 static int fastload_num;
5090 static struct FastLoad *fastload;
5092 static void free_fastload(void)
5094 if (fastload != NULL)
5096 int i;
5097 for (i = 0; i < fastload_num; i++)
5099 if (fastload[i].data)
5100 free(fastload[i].data);
5102 free(fastload);
5103 fastload = NULL;
5110 COMMAND_HANDLER(handle_fast_load_image_command)
5112 uint8_t *buffer;
5113 size_t buf_cnt;
5114 uint32_t image_size;
5115 uint32_t min_address = 0;
5116 uint32_t max_address = 0xffffffff;
5117 int i;
5119 struct image image;
5121 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5122 &image, &min_address, &max_address);
5123 if (ERROR_OK != retval)
5124 return retval;
5126 struct duration bench;
5127 duration_start(&bench);
5129 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5130 if (retval != ERROR_OK)
5132 return retval;
5135 image_size = 0x0;
5136 retval = ERROR_OK;
5137 fastload_num = image.num_sections;
5138 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5139 if (fastload == NULL)
5141 command_print(CMD_CTX, "out of memory");
5142 image_close(&image);
5143 return ERROR_FAIL;
5145 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5146 for (i = 0; i < image.num_sections; i++)
5148 buffer = malloc(image.sections[i].size);
5149 if (buffer == NULL)
5151 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5152 (int)(image.sections[i].size));
5153 retval = ERROR_FAIL;
5154 break;
5157 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
5159 free(buffer);
5160 break;
5163 uint32_t offset = 0;
5164 uint32_t length = buf_cnt;
5167 /* DANGER!!! beware of unsigned comparision here!!! */
5169 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
5170 (image.sections[i].base_address < max_address))
5172 if (image.sections[i].base_address < min_address)
5174 /* clip addresses below */
5175 offset += min_address-image.sections[i].base_address;
5176 length -= offset;
5179 if (image.sections[i].base_address + buf_cnt > max_address)
5181 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5184 fastload[i].address = image.sections[i].base_address + offset;
5185 fastload[i].data = malloc(length);
5186 if (fastload[i].data == NULL)
5188 free(buffer);
5189 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5190 length);
5191 retval = ERROR_FAIL;
5192 break;
5194 memcpy(fastload[i].data, buffer + offset, length);
5195 fastload[i].length = length;
5197 image_size += length;
5198 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5199 (unsigned int)length,
5200 ((unsigned int)(image.sections[i].base_address + offset)));
5203 free(buffer);
5206 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5208 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5209 "in %fs (%0.3f KiB/s)", image_size,
5210 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5212 command_print(CMD_CTX,
5213 "WARNING: image has not been loaded to target!"
5214 "You can issue a 'fast_load' to finish loading.");
5217 image_close(&image);
5219 if (retval != ERROR_OK)
5221 free_fastload();
5224 return retval;
5227 COMMAND_HANDLER(handle_fast_load_command)
5229 if (CMD_ARGC > 0)
5230 return ERROR_COMMAND_SYNTAX_ERROR;
5231 if (fastload == NULL)
5233 LOG_ERROR("No image in memory");
5234 return ERROR_FAIL;
5236 int i;
5237 int ms = timeval_ms();
5238 int size = 0;
5239 int retval = ERROR_OK;
5240 for (i = 0; i < fastload_num;i++)
5242 struct target *target = get_current_target(CMD_CTX);
5243 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5244 (unsigned int)(fastload[i].address),
5245 (unsigned int)(fastload[i].length));
5246 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5247 if (retval != ERROR_OK)
5249 break;
5251 size += fastload[i].length;
5253 if (retval == ERROR_OK)
5255 int after = timeval_ms();
5256 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5258 return retval;
5261 static const struct command_registration target_command_handlers[] = {
5263 .name = "targets",
5264 .handler = handle_targets_command,
5265 .mode = COMMAND_ANY,
5266 .help = "change current default target (one parameter) "
5267 "or prints table of all targets (no parameters)",
5268 .usage = "[target]",
5271 .name = "target",
5272 .mode = COMMAND_CONFIG,
5273 .help = "configure target",
5275 .chain = target_subcommand_handlers,
5277 COMMAND_REGISTRATION_DONE
5280 int target_register_commands(struct command_context *cmd_ctx)
5282 return register_commands(cmd_ctx, NULL, target_command_handlers);
5285 static bool target_reset_nag = true;
5287 bool get_target_reset_nag(void)
5289 return target_reset_nag;
5292 COMMAND_HANDLER(handle_target_reset_nag)
5294 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5295 &target_reset_nag, "Nag after each reset about options to improve "
5296 "performance");
5299 static const struct command_registration target_exec_command_handlers[] = {
5301 .name = "fast_load_image",
5302 .handler = handle_fast_load_image_command,
5303 .mode = COMMAND_ANY,
5304 .help = "Load image into server memory for later use by "
5305 "fast_load; primarily for profiling",
5306 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5307 "[min_address [max_length]]",
5310 .name = "fast_load",
5311 .handler = handle_fast_load_command,
5312 .mode = COMMAND_EXEC,
5313 .help = "loads active fast load image to current target "
5314 "- mainly for profiling purposes",
5317 .name = "profile",
5318 .handler = handle_profile_command,
5319 .mode = COMMAND_EXEC,
5320 .help = "profiling samples the CPU PC",
5322 /** @todo don't register virt2phys() unless target supports it */
5324 .name = "virt2phys",
5325 .handler = handle_virt2phys_command,
5326 .mode = COMMAND_ANY,
5327 .help = "translate a virtual address into a physical address",
5328 .usage = "virtual_address",
5331 .name = "reg",
5332 .handler = handle_reg_command,
5333 .mode = COMMAND_EXEC,
5334 .help = "display or set a register; with no arguments, "
5335 "displays all registers and their values",
5336 .usage = "[(register_name|register_number) [value]]",
5339 .name = "poll",
5340 .handler = handle_poll_command,
5341 .mode = COMMAND_EXEC,
5342 .help = "poll target state; or reconfigure background polling",
5343 .usage = "['on'|'off']",
5346 .name = "wait_halt",
5347 .handler = handle_wait_halt_command,
5348 .mode = COMMAND_EXEC,
5349 .help = "wait up to the specified number of milliseconds "
5350 "(default 5) for a previously requested halt",
5351 .usage = "[milliseconds]",
5354 .name = "halt",
5355 .handler = handle_halt_command,
5356 .mode = COMMAND_EXEC,
5357 .help = "request target to halt, then wait up to the specified"
5358 "number of milliseconds (default 5) for it to complete",
5359 .usage = "[milliseconds]",
5362 .name = "resume",
5363 .handler = handle_resume_command,
5364 .mode = COMMAND_EXEC,
5365 .help = "resume target execution from current PC or address",
5366 .usage = "[address]",
5369 .name = "reset",
5370 .handler = handle_reset_command,
5371 .mode = COMMAND_EXEC,
5372 .usage = "[run|halt|init]",
5373 .help = "Reset all targets into the specified mode."
5374 "Default reset mode is run, if not given.",
5377 .name = "soft_reset_halt",
5378 .handler = handle_soft_reset_halt_command,
5379 .mode = COMMAND_EXEC,
5380 .help = "halt the target and do a soft reset",
5383 .name = "step",
5384 .handler = handle_step_command,
5385 .mode = COMMAND_EXEC,
5386 .help = "step one instruction from current PC or address",
5387 .usage = "[address]",
5390 .name = "mdw",
5391 .handler = handle_md_command,
5392 .mode = COMMAND_EXEC,
5393 .help = "display memory words",
5394 .usage = "['phys'] address [count]",
5397 .name = "mdh",
5398 .handler = handle_md_command,
5399 .mode = COMMAND_EXEC,
5400 .help = "display memory half-words",
5401 .usage = "['phys'] address [count]",
5404 .name = "mdb",
5405 .handler = handle_md_command,
5406 .mode = COMMAND_EXEC,
5407 .help = "display memory bytes",
5408 .usage = "['phys'] address [count]",
5411 .name = "mww",
5412 .handler = handle_mw_command,
5413 .mode = COMMAND_EXEC,
5414 .help = "write memory word",
5415 .usage = "['phys'] address value [count]",
5418 .name = "mwh",
5419 .handler = handle_mw_command,
5420 .mode = COMMAND_EXEC,
5421 .help = "write memory half-word",
5422 .usage = "['phys'] address value [count]",
5425 .name = "mwb",
5426 .handler = handle_mw_command,
5427 .mode = COMMAND_EXEC,
5428 .help = "write memory byte",
5429 .usage = "['phys'] address value [count]",
5432 .name = "bp",
5433 .handler = handle_bp_command,
5434 .mode = COMMAND_EXEC,
5435 .help = "list or set hardware or software breakpoint",
5436 .usage = "[address length ['hw']]",
5439 .name = "rbp",
5440 .handler = handle_rbp_command,
5441 .mode = COMMAND_EXEC,
5442 .help = "remove breakpoint",
5443 .usage = "address",
5446 .name = "wp",
5447 .handler = handle_wp_command,
5448 .mode = COMMAND_EXEC,
5449 .help = "list (no params) or create watchpoints",
5450 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5453 .name = "rwp",
5454 .handler = handle_rwp_command,
5455 .mode = COMMAND_EXEC,
5456 .help = "remove watchpoint",
5457 .usage = "address",
5460 .name = "load_image",
5461 .handler = handle_load_image_command,
5462 .mode = COMMAND_EXEC,
5463 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5464 "[min_address] [max_length]",
5467 .name = "dump_image",
5468 .handler = handle_dump_image_command,
5469 .mode = COMMAND_EXEC,
5470 .usage = "filename address size",
5473 .name = "verify_image",
5474 .handler = handle_verify_image_command,
5475 .mode = COMMAND_EXEC,
5476 .usage = "filename [offset [type]]",
5479 .name = "test_image",
5480 .handler = handle_test_image_command,
5481 .mode = COMMAND_EXEC,
5482 .usage = "filename [offset [type]]",
5485 .name = "mem2array",
5486 .mode = COMMAND_EXEC,
5487 .jim_handler = jim_mem2array,
5488 .help = "read 8/16/32 bit memory and return as a TCL array "
5489 "for script processing",
5490 .usage = "arrayname bitwidth address count",
5493 .name = "array2mem",
5494 .mode = COMMAND_EXEC,
5495 .jim_handler = jim_array2mem,
5496 .help = "convert a TCL array to memory locations "
5497 "and write the 8/16/32 bit values",
5498 .usage = "arrayname bitwidth address count",
5501 .name = "reset_nag",
5502 .handler = handle_target_reset_nag,
5503 .mode = COMMAND_ANY,
5504 .help = "Nag after each reset about options that could have been "
5505 "enabled to improve performance. ",
5506 .usage = "['enable'|'disable']",
5508 COMMAND_REGISTRATION_DONE
5510 static int target_register_user_commands(struct command_context *cmd_ctx)
5512 int retval = ERROR_OK;
5513 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5514 return retval;
5516 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5517 return retval;
5520 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);