target: add -dbgbase option to target configuration
[openocd/openocdswd.git] / src / target / target.c
blobdf38c837b7e0bba7fa5a76b994b7746b1c3e228c
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
10 * *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
13 * *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
16 * *
17 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
21 * *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
26 * *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program; if not, write to the *
29 * Free Software Foundation, Inc., *
30 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
31 ***************************************************************************/
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
36 #include <helper/time_support.h>
37 #include <jtag/jtag.h>
38 #include <flash/nor/core.h>
40 #include "target.h"
41 #include "target_type.h"
42 #include "target_request.h"
43 #include "breakpoints.h"
44 #include "register.h"
45 #include "trace.h"
46 #include "image.h"
49 static int target_read_buffer_default(struct target *target, uint32_t address,
50 uint32_t size, uint8_t *buffer);
51 static int target_write_buffer_default(struct target *target, uint32_t address,
52 uint32_t size, uint8_t *buffer);
53 static int target_array2mem(Jim_Interp *interp, struct target *target,
54 int argc, Jim_Obj *const *argv);
55 static int target_mem2array(Jim_Interp *interp, struct target *target,
56 int argc, Jim_Obj *const *argv);
57 static int target_register_user_commands(struct command_context *cmd_ctx);
59 /* targets */
60 extern struct target_type arm7tdmi_target;
61 extern struct target_type arm720t_target;
62 extern struct target_type arm9tdmi_target;
63 extern struct target_type arm920t_target;
64 extern struct target_type arm966e_target;
65 extern struct target_type arm946e_target;
66 extern struct target_type arm926ejs_target;
67 extern struct target_type fa526_target;
68 extern struct target_type feroceon_target;
69 extern struct target_type dragonite_target;
70 extern struct target_type xscale_target;
71 extern struct target_type cortexm3_target;
72 extern struct target_type cortexa8_target;
73 extern struct target_type arm11_target;
74 extern struct target_type mips_m4k_target;
75 extern struct target_type avr_target;
76 extern struct target_type dsp563xx_target;
77 extern struct target_type testee_target;
78 extern struct target_type avr32_ap7k_target;
80 static struct target_type *target_types[] =
82 &arm7tdmi_target,
83 &arm9tdmi_target,
84 &arm920t_target,
85 &arm720t_target,
86 &arm966e_target,
87 &arm946e_target,
88 &arm926ejs_target,
89 &fa526_target,
90 &feroceon_target,
91 &dragonite_target,
92 &xscale_target,
93 &cortexm3_target,
94 &cortexa8_target,
95 &arm11_target,
96 &mips_m4k_target,
97 &avr_target,
98 &dsp563xx_target,
99 &testee_target,
100 &avr32_ap7k_target,
101 NULL,
104 struct target *all_targets = NULL;
105 static struct target_event_callback *target_event_callbacks = NULL;
106 static struct target_timer_callback *target_timer_callbacks = NULL;
107 static const int polling_interval = 100;
109 static const Jim_Nvp nvp_assert[] = {
110 { .name = "assert", NVP_ASSERT },
111 { .name = "deassert", NVP_DEASSERT },
112 { .name = "T", NVP_ASSERT },
113 { .name = "F", NVP_DEASSERT },
114 { .name = "t", NVP_ASSERT },
115 { .name = "f", NVP_DEASSERT },
116 { .name = NULL, .value = -1 }
119 static const Jim_Nvp nvp_error_target[] = {
120 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
121 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
122 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
123 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
124 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
125 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
126 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
127 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
128 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
129 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
130 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
131 { .value = -1, .name = NULL }
134 static const char *target_strerror_safe(int err)
136 const Jim_Nvp *n;
138 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
139 if (n->name == NULL) {
140 return "unknown";
141 } else {
142 return n->name;
146 static const Jim_Nvp nvp_target_event[] = {
147 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
148 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
150 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
151 { .value = TARGET_EVENT_HALTED, .name = "halted" },
152 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
153 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
154 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
156 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
157 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
159 /* historical name */
161 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
163 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
164 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
165 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
166 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
167 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
168 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
169 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
170 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
171 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
172 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
173 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
175 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
176 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
178 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
179 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
181 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
182 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
184 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
185 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
187 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
188 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
190 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
191 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
192 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
194 { .name = NULL, .value = -1 }
197 static const Jim_Nvp nvp_target_state[] = {
198 { .name = "unknown", .value = TARGET_UNKNOWN },
199 { .name = "running", .value = TARGET_RUNNING },
200 { .name = "halted", .value = TARGET_HALTED },
201 { .name = "reset", .value = TARGET_RESET },
202 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
203 { .name = NULL, .value = -1 },
206 static const Jim_Nvp nvp_target_debug_reason [] = {
207 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
208 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
209 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
210 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
211 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
212 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
213 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
214 { .name = NULL, .value = -1 },
217 static const Jim_Nvp nvp_target_endian[] = {
218 { .name = "big", .value = TARGET_BIG_ENDIAN },
219 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
220 { .name = "be", .value = TARGET_BIG_ENDIAN },
221 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
222 { .name = NULL, .value = -1 },
225 static const Jim_Nvp nvp_reset_modes[] = {
226 { .name = "unknown", .value = RESET_UNKNOWN },
227 { .name = "run" , .value = RESET_RUN },
228 { .name = "halt" , .value = RESET_HALT },
229 { .name = "init" , .value = RESET_INIT },
230 { .name = NULL , .value = -1 },
233 const char *debug_reason_name(struct target *t)
235 const char *cp;
237 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
238 t->debug_reason)->name;
239 if (!cp) {
240 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
241 cp = "(*BUG*unknown*BUG*)";
243 return cp;
246 const char *
247 target_state_name( struct target *t )
249 const char *cp;
250 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
251 if( !cp ){
252 LOG_ERROR("Invalid target state: %d", (int)(t->state));
253 cp = "(*BUG*unknown*BUG*)";
255 return cp;
258 /* determine the number of the new target */
259 static int new_target_number(void)
261 struct target *t;
262 int x;
264 /* number is 0 based */
265 x = -1;
266 t = all_targets;
267 while (t) {
268 if (x < t->target_number) {
269 x = t->target_number;
271 t = t->next;
273 return x + 1;
276 /* read a uint32_t from a buffer in target memory endianness */
277 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
279 if (target->endianness == TARGET_LITTLE_ENDIAN)
280 return le_to_h_u32(buffer);
281 else
282 return be_to_h_u32(buffer);
285 /* read a uint24_t from a buffer in target memory endianness */
286 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
288 if (target->endianness == TARGET_LITTLE_ENDIAN)
289 return le_to_h_u24(buffer);
290 else
291 return be_to_h_u24(buffer);
294 /* read a uint16_t from a buffer in target memory endianness */
295 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
297 if (target->endianness == TARGET_LITTLE_ENDIAN)
298 return le_to_h_u16(buffer);
299 else
300 return be_to_h_u16(buffer);
303 /* read a uint8_t from a buffer in target memory endianness */
304 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
306 return *buffer & 0x0ff;
309 /* write a uint32_t to a buffer in target memory endianness */
310 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
312 if (target->endianness == TARGET_LITTLE_ENDIAN)
313 h_u32_to_le(buffer, value);
314 else
315 h_u32_to_be(buffer, value);
318 /* write a uint24_t to a buffer in target memory endianness */
319 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
321 if (target->endianness == TARGET_LITTLE_ENDIAN)
322 h_u24_to_le(buffer, value);
323 else
324 h_u24_to_be(buffer, value);
327 /* write a uint16_t to a buffer in target memory endianness */
328 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
330 if (target->endianness == TARGET_LITTLE_ENDIAN)
331 h_u16_to_le(buffer, value);
332 else
333 h_u16_to_be(buffer, value);
336 /* write a uint8_t to a buffer in target memory endianness */
337 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
339 *buffer = value;
342 /* return a pointer to a configured target; id is name or number */
343 struct target *get_target(const char *id)
345 struct target *target;
347 /* try as tcltarget name */
348 for (target = all_targets; target; target = target->next) {
349 if (target->cmd_name == NULL)
350 continue;
351 if (strcmp(id, target->cmd_name) == 0)
352 return target;
355 /* It's OK to remove this fallback sometime after August 2010 or so */
357 /* no match, try as number */
358 unsigned num;
359 if (parse_uint(id, &num) != ERROR_OK)
360 return NULL;
362 for (target = all_targets; target; target = target->next) {
363 if (target->target_number == (int)num) {
364 LOG_WARNING("use '%s' as target identifier, not '%u'",
365 target->cmd_name, num);
366 return target;
370 return NULL;
373 /* returns a pointer to the n-th configured target */
374 static struct target *get_target_by_num(int num)
376 struct target *target = all_targets;
378 while (target) {
379 if (target->target_number == num) {
380 return target;
382 target = target->next;
385 return NULL;
388 struct target* get_current_target(struct command_context *cmd_ctx)
390 struct target *target = get_target_by_num(cmd_ctx->current_target);
392 if (target == NULL)
394 LOG_ERROR("BUG: current_target out of bounds");
395 exit(-1);
398 return target;
401 int target_poll(struct target *target)
403 int retval;
405 /* We can't poll until after examine */
406 if (!target_was_examined(target))
408 /* Fail silently lest we pollute the log */
409 return ERROR_FAIL;
412 retval = target->type->poll(target);
413 if (retval != ERROR_OK)
414 return retval;
416 if (target->halt_issued)
418 if (target->state == TARGET_HALTED)
420 target->halt_issued = false;
421 } else
423 long long t = timeval_ms() - target->halt_issued_time;
424 if (t>1000)
426 target->halt_issued = false;
427 LOG_INFO("Halt timed out, wake up GDB.");
428 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
433 return ERROR_OK;
436 int target_halt(struct target *target)
438 int retval;
439 /* We can't poll until after examine */
440 if (!target_was_examined(target))
442 LOG_ERROR("Target not examined yet");
443 return ERROR_FAIL;
446 retval = target->type->halt(target);
447 if (retval != ERROR_OK)
448 return retval;
450 target->halt_issued = true;
451 target->halt_issued_time = timeval_ms();
453 return ERROR_OK;
457 * Make the target (re)start executing using its saved execution
458 * context (possibly with some modifications).
460 * @param target Which target should start executing.
461 * @param current True to use the target's saved program counter instead
462 * of the address parameter
463 * @param address Optionally used as the program counter.
464 * @param handle_breakpoints True iff breakpoints at the resumption PC
465 * should be skipped. (For example, maybe execution was stopped by
466 * such a breakpoint, in which case it would be counterprodutive to
467 * let it re-trigger.
468 * @param debug_execution False if all working areas allocated by OpenOCD
469 * should be released and/or restored to their original contents.
470 * (This would for example be true to run some downloaded "helper"
471 * algorithm code, which resides in one such working buffer and uses
472 * another for data storage.)
474 * @todo Resolve the ambiguity about what the "debug_execution" flag
475 * signifies. For example, Target implementations don't agree on how
476 * it relates to invalidation of the register cache, or to whether
477 * breakpoints and watchpoints should be enabled. (It would seem wrong
478 * to enable breakpoints when running downloaded "helper" algorithms
479 * (debug_execution true), since the breakpoints would be set to match
480 * target firmware being debugged, not the helper algorithm.... and
481 * enabling them could cause such helpers to malfunction (for example,
482 * by overwriting data with a breakpoint instruction. On the other
483 * hand the infrastructure for running such helpers might use this
484 * procedure but rely on hardware breakpoint to detect termination.)
486 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
488 int retval;
490 /* We can't poll until after examine */
491 if (!target_was_examined(target))
493 LOG_ERROR("Target not examined yet");
494 return ERROR_FAIL;
497 /* note that resume *must* be asynchronous. The CPU can halt before
498 * we poll. The CPU can even halt at the current PC as a result of
499 * a software breakpoint being inserted by (a bug?) the application.
501 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
502 return retval;
504 return retval;
507 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
509 char buf[100];
510 int retval;
511 Jim_Nvp *n;
512 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
513 if (n->name == NULL) {
514 LOG_ERROR("invalid reset mode");
515 return ERROR_FAIL;
518 /* disable polling during reset to make reset event scripts
519 * more predictable, i.e. dr/irscan & pathmove in events will
520 * not have JTAG operations injected into the middle of a sequence.
522 bool save_poll = jtag_poll_get_enabled();
524 jtag_poll_set_enabled(false);
526 sprintf(buf, "ocd_process_reset %s", n->name);
527 retval = Jim_Eval(cmd_ctx->interp, buf);
529 jtag_poll_set_enabled(save_poll);
531 if (retval != JIM_OK) {
532 Jim_MakeErrorMessage(cmd_ctx->interp);
533 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
534 return ERROR_FAIL;
537 /* We want any events to be processed before the prompt */
538 retval = target_call_timer_callbacks_now();
540 struct target *target;
541 for (target = all_targets; target; target = target->next) {
542 target->type->check_reset(target);
545 return retval;
548 static int identity_virt2phys(struct target *target,
549 uint32_t virtual, uint32_t *physical)
551 *physical = virtual;
552 return ERROR_OK;
555 static int no_mmu(struct target *target, int *enabled)
557 *enabled = 0;
558 return ERROR_OK;
561 static int default_examine(struct target *target)
563 target_set_examined(target);
564 return ERROR_OK;
567 /* no check by default */
568 static int default_check_reset(struct target *target)
570 return ERROR_OK;
573 int target_examine_one(struct target *target)
575 return target->type->examine(target);
578 static int jtag_enable_callback(enum jtag_event event, void *priv)
580 struct target *target = priv;
582 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
583 return ERROR_OK;
585 jtag_unregister_event_callback(jtag_enable_callback, target);
586 return target_examine_one(target);
590 /* Targets that correctly implement init + examine, i.e.
591 * no communication with target during init:
593 * XScale
595 int target_examine(void)
597 int retval = ERROR_OK;
598 struct target *target;
600 for (target = all_targets; target; target = target->next)
602 /* defer examination, but don't skip it */
603 if (!target->tap->enabled) {
604 jtag_register_event_callback(jtag_enable_callback,
605 target);
606 continue;
608 if ((retval = target_examine_one(target)) != ERROR_OK)
609 return retval;
611 return retval;
613 const char *target_type_name(struct target *target)
615 return target->type->name;
618 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
620 if (!target_was_examined(target))
622 LOG_ERROR("Target not examined yet");
623 return ERROR_FAIL;
625 return target->type->write_memory_imp(target, address, size, count, buffer);
628 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
630 if (!target_was_examined(target))
632 LOG_ERROR("Target not examined yet");
633 return ERROR_FAIL;
635 return target->type->read_memory_imp(target, address, size, count, buffer);
638 static int target_soft_reset_halt_imp(struct target *target)
640 if (!target_was_examined(target))
642 LOG_ERROR("Target not examined yet");
643 return ERROR_FAIL;
645 if (!target->type->soft_reset_halt_imp) {
646 LOG_ERROR("Target %s does not support soft_reset_halt",
647 target_name(target));
648 return ERROR_FAIL;
650 return target->type->soft_reset_halt_imp(target);
654 * Downloads a target-specific native code algorithm to the target,
655 * and executes it. * Note that some targets may need to set up, enable,
656 * and tear down a breakpoint (hard or * soft) to detect algorithm
657 * termination, while others may support lower overhead schemes where
658 * soft breakpoints embedded in the algorithm automatically terminate the
659 * algorithm.
661 * @param target used to run the algorithm
662 * @param arch_info target-specific description of the algorithm.
664 int target_run_algorithm(struct target *target,
665 int num_mem_params, struct mem_param *mem_params,
666 int num_reg_params, struct reg_param *reg_param,
667 uint32_t entry_point, uint32_t exit_point,
668 int timeout_ms, void *arch_info)
670 int retval = ERROR_FAIL;
672 if (!target_was_examined(target))
674 LOG_ERROR("Target not examined yet");
675 goto done;
677 if (!target->type->run_algorithm) {
678 LOG_ERROR("Target type '%s' does not support %s",
679 target_type_name(target), __func__);
680 goto done;
683 target->running_alg = true;
684 retval = target->type->run_algorithm(target,
685 num_mem_params, mem_params,
686 num_reg_params, reg_param,
687 entry_point, exit_point, timeout_ms, arch_info);
688 target->running_alg = false;
690 done:
691 return retval;
695 int target_read_memory(struct target *target,
696 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
698 return target->type->read_memory(target, address, size, count, buffer);
701 static int target_read_phys_memory(struct target *target,
702 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
704 return target->type->read_phys_memory(target, address, size, count, buffer);
707 int target_write_memory(struct target *target,
708 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
710 return target->type->write_memory(target, address, size, count, buffer);
713 static int target_write_phys_memory(struct target *target,
714 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
716 return target->type->write_phys_memory(target, address, size, count, buffer);
719 int target_bulk_write_memory(struct target *target,
720 uint32_t address, uint32_t count, uint8_t *buffer)
722 return target->type->bulk_write_memory(target, address, count, buffer);
725 int target_add_breakpoint(struct target *target,
726 struct breakpoint *breakpoint)
728 if (target->state != TARGET_HALTED) {
729 LOG_WARNING("target %s is not halted", target->cmd_name);
730 return ERROR_TARGET_NOT_HALTED;
732 return target->type->add_breakpoint(target, breakpoint);
734 int target_remove_breakpoint(struct target *target,
735 struct breakpoint *breakpoint)
737 return target->type->remove_breakpoint(target, breakpoint);
740 int target_add_watchpoint(struct target *target,
741 struct watchpoint *watchpoint)
743 if (target->state != TARGET_HALTED) {
744 LOG_WARNING("target %s is not halted", target->cmd_name);
745 return ERROR_TARGET_NOT_HALTED;
747 return target->type->add_watchpoint(target, watchpoint);
749 int target_remove_watchpoint(struct target *target,
750 struct watchpoint *watchpoint)
752 return target->type->remove_watchpoint(target, watchpoint);
755 int target_get_gdb_reg_list(struct target *target,
756 struct reg **reg_list[], int *reg_list_size)
758 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
760 int target_step(struct target *target,
761 int current, uint32_t address, int handle_breakpoints)
763 return target->type->step(target, current, address, handle_breakpoints);
768 * Reset the @c examined flag for the given target.
769 * Pure paranoia -- targets are zeroed on allocation.
771 static void target_reset_examined(struct target *target)
773 target->examined = false;
776 static int
777 err_read_phys_memory(struct target *target, uint32_t address,
778 uint32_t size, uint32_t count, uint8_t *buffer)
780 LOG_ERROR("Not implemented: %s", __func__);
781 return ERROR_FAIL;
784 static int
785 err_write_phys_memory(struct target *target, uint32_t address,
786 uint32_t size, uint32_t count, uint8_t *buffer)
788 LOG_ERROR("Not implemented: %s", __func__);
789 return ERROR_FAIL;
792 static int handle_target(void *priv);
794 static int target_init_one(struct command_context *cmd_ctx,
795 struct target *target)
797 target_reset_examined(target);
799 struct target_type *type = target->type;
800 if (type->examine == NULL)
801 type->examine = default_examine;
803 if (type->check_reset== NULL)
804 type->check_reset = default_check_reset;
806 int retval = type->init_target(cmd_ctx, target);
807 if (ERROR_OK != retval)
809 LOG_ERROR("target '%s' init failed", target_name(target));
810 return retval;
814 * @todo get rid of those *memory_imp() methods, now that all
815 * callers are using target_*_memory() accessors ... and make
816 * sure the "physical" paths handle the same issues.
818 /* a non-invasive way(in terms of patches) to add some code that
819 * runs before the type->write/read_memory implementation
821 type->write_memory_imp = target->type->write_memory;
822 type->write_memory = target_write_memory_imp;
824 type->read_memory_imp = target->type->read_memory;
825 type->read_memory = target_read_memory_imp;
827 type->soft_reset_halt_imp = target->type->soft_reset_halt;
828 type->soft_reset_halt = target_soft_reset_halt_imp;
830 /* Sanity-check MMU support ... stub in what we must, to help
831 * implement it in stages, but warn if we need to do so.
833 if (type->mmu)
835 if (type->write_phys_memory == NULL)
837 LOG_ERROR("type '%s' is missing write_phys_memory",
838 type->name);
839 type->write_phys_memory = err_write_phys_memory;
841 if (type->read_phys_memory == NULL)
843 LOG_ERROR("type '%s' is missing read_phys_memory",
844 type->name);
845 type->read_phys_memory = err_read_phys_memory;
847 if (type->virt2phys == NULL)
849 LOG_ERROR("type '%s' is missing virt2phys", type->name);
850 type->virt2phys = identity_virt2phys;
853 else
855 /* Make sure no-MMU targets all behave the same: make no
856 * distinction between physical and virtual addresses, and
857 * ensure that virt2phys() is always an identity mapping.
859 if (type->write_phys_memory || type->read_phys_memory
860 || type->virt2phys)
862 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
865 type->mmu = no_mmu;
866 type->write_phys_memory = type->write_memory;
867 type->read_phys_memory = type->read_memory;
868 type->virt2phys = identity_virt2phys;
871 if (target->type->read_buffer == NULL)
872 target->type->read_buffer = target_read_buffer_default;
874 if (target->type->write_buffer == NULL)
875 target->type->write_buffer = target_write_buffer_default;
877 return ERROR_OK;
880 static int target_init(struct command_context *cmd_ctx)
882 struct target *target;
883 int retval;
885 for (target = all_targets; target; target = target->next)
887 retval = target_init_one(cmd_ctx, target);
888 if (ERROR_OK != retval)
889 return retval;
892 if (!all_targets)
893 return ERROR_OK;
895 retval = target_register_user_commands(cmd_ctx);
896 if (ERROR_OK != retval)
897 return retval;
899 retval = target_register_timer_callback(&handle_target,
900 polling_interval, 1, cmd_ctx->interp);
901 if (ERROR_OK != retval)
902 return retval;
904 return ERROR_OK;
907 COMMAND_HANDLER(handle_target_init_command)
909 if (CMD_ARGC != 0)
910 return ERROR_COMMAND_SYNTAX_ERROR;
912 static bool target_initialized = false;
913 if (target_initialized)
915 LOG_INFO("'target init' has already been called");
916 return ERROR_OK;
918 target_initialized = true;
920 LOG_DEBUG("Initializing targets...");
921 return target_init(CMD_CTX);
924 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
926 struct target_event_callback **callbacks_p = &target_event_callbacks;
928 if (callback == NULL)
930 return ERROR_INVALID_ARGUMENTS;
933 if (*callbacks_p)
935 while ((*callbacks_p)->next)
936 callbacks_p = &((*callbacks_p)->next);
937 callbacks_p = &((*callbacks_p)->next);
940 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
941 (*callbacks_p)->callback = callback;
942 (*callbacks_p)->priv = priv;
943 (*callbacks_p)->next = NULL;
945 return ERROR_OK;
948 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
950 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
951 struct timeval now;
953 if (callback == NULL)
955 return ERROR_INVALID_ARGUMENTS;
958 if (*callbacks_p)
960 while ((*callbacks_p)->next)
961 callbacks_p = &((*callbacks_p)->next);
962 callbacks_p = &((*callbacks_p)->next);
965 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
966 (*callbacks_p)->callback = callback;
967 (*callbacks_p)->periodic = periodic;
968 (*callbacks_p)->time_ms = time_ms;
970 gettimeofday(&now, NULL);
971 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
972 time_ms -= (time_ms % 1000);
973 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
974 if ((*callbacks_p)->when.tv_usec > 1000000)
976 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
977 (*callbacks_p)->when.tv_sec += 1;
980 (*callbacks_p)->priv = priv;
981 (*callbacks_p)->next = NULL;
983 return ERROR_OK;
986 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
988 struct target_event_callback **p = &target_event_callbacks;
989 struct target_event_callback *c = target_event_callbacks;
991 if (callback == NULL)
993 return ERROR_INVALID_ARGUMENTS;
996 while (c)
998 struct target_event_callback *next = c->next;
999 if ((c->callback == callback) && (c->priv == priv))
1001 *p = next;
1002 free(c);
1003 return ERROR_OK;
1005 else
1006 p = &(c->next);
1007 c = next;
1010 return ERROR_OK;
1013 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1015 struct target_timer_callback **p = &target_timer_callbacks;
1016 struct target_timer_callback *c = target_timer_callbacks;
1018 if (callback == NULL)
1020 return ERROR_INVALID_ARGUMENTS;
1023 while (c)
1025 struct target_timer_callback *next = c->next;
1026 if ((c->callback == callback) && (c->priv == priv))
1028 *p = next;
1029 free(c);
1030 return ERROR_OK;
1032 else
1033 p = &(c->next);
1034 c = next;
1037 return ERROR_OK;
1040 int target_call_event_callbacks(struct target *target, enum target_event event)
1042 struct target_event_callback *callback = target_event_callbacks;
1043 struct target_event_callback *next_callback;
1045 if (event == TARGET_EVENT_HALTED)
1047 /* execute early halted first */
1048 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1051 LOG_DEBUG("target event %i (%s)",
1052 event,
1053 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1055 target_handle_event(target, event);
1057 while (callback)
1059 next_callback = callback->next;
1060 callback->callback(target, event, callback->priv);
1061 callback = next_callback;
1064 return ERROR_OK;
1067 static int target_timer_callback_periodic_restart(
1068 struct target_timer_callback *cb, struct timeval *now)
1070 int time_ms = cb->time_ms;
1071 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1072 time_ms -= (time_ms % 1000);
1073 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1074 if (cb->when.tv_usec > 1000000)
1076 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1077 cb->when.tv_sec += 1;
1079 return ERROR_OK;
1082 static int target_call_timer_callback(struct target_timer_callback *cb,
1083 struct timeval *now)
1085 cb->callback(cb->priv);
1087 if (cb->periodic)
1088 return target_timer_callback_periodic_restart(cb, now);
1090 return target_unregister_timer_callback(cb->callback, cb->priv);
1093 static int target_call_timer_callbacks_check_time(int checktime)
1095 keep_alive();
1097 struct timeval now;
1098 gettimeofday(&now, NULL);
1100 struct target_timer_callback *callback = target_timer_callbacks;
1101 while (callback)
1103 // cleaning up may unregister and free this callback
1104 struct target_timer_callback *next_callback = callback->next;
1106 bool call_it = callback->callback &&
1107 ((!checktime && callback->periodic) ||
1108 now.tv_sec > callback->when.tv_sec ||
1109 (now.tv_sec == callback->when.tv_sec &&
1110 now.tv_usec >= callback->when.tv_usec));
1112 if (call_it)
1114 int retval = target_call_timer_callback(callback, &now);
1115 if (retval != ERROR_OK)
1116 return retval;
1119 callback = next_callback;
1122 return ERROR_OK;
1125 int target_call_timer_callbacks(void)
1127 return target_call_timer_callbacks_check_time(1);
1130 /* invoke periodic callbacks immediately */
1131 int target_call_timer_callbacks_now(void)
1133 return target_call_timer_callbacks_check_time(0);
1136 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1138 struct working_area *c = target->working_areas;
1139 struct working_area *new_wa = NULL;
1141 /* Reevaluate working area address based on MMU state*/
1142 if (target->working_areas == NULL)
1144 int retval;
1145 int enabled;
1147 retval = target->type->mmu(target, &enabled);
1148 if (retval != ERROR_OK)
1150 return retval;
1153 if (!enabled) {
1154 if (target->working_area_phys_spec) {
1155 LOG_DEBUG("MMU disabled, using physical "
1156 "address for working memory 0x%08x",
1157 (unsigned)target->working_area_phys);
1158 target->working_area = target->working_area_phys;
1159 } else {
1160 LOG_ERROR("No working memory available. "
1161 "Specify -work-area-phys to target.");
1162 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1164 } else {
1165 if (target->working_area_virt_spec) {
1166 LOG_DEBUG("MMU enabled, using virtual "
1167 "address for working memory 0x%08x",
1168 (unsigned)target->working_area_virt);
1169 target->working_area = target->working_area_virt;
1170 } else {
1171 LOG_ERROR("No working memory available. "
1172 "Specify -work-area-virt to target.");
1173 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1178 /* only allocate multiples of 4 byte */
1179 if (size % 4)
1181 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1182 size = (size + 3) & (~3);
1185 /* see if there's already a matching working area */
1186 while (c)
1188 if ((c->free) && (c->size == size))
1190 new_wa = c;
1191 break;
1193 c = c->next;
1196 /* if not, allocate a new one */
1197 if (!new_wa)
1199 struct working_area **p = &target->working_areas;
1200 uint32_t first_free = target->working_area;
1201 uint32_t free_size = target->working_area_size;
1203 c = target->working_areas;
1204 while (c)
1206 first_free += c->size;
1207 free_size -= c->size;
1208 p = &c->next;
1209 c = c->next;
1212 if (free_size < size)
1214 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1217 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1219 new_wa = malloc(sizeof(struct working_area));
1220 new_wa->next = NULL;
1221 new_wa->size = size;
1222 new_wa->address = first_free;
1224 if (target->backup_working_area)
1226 int retval;
1227 new_wa->backup = malloc(new_wa->size);
1228 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1230 free(new_wa->backup);
1231 free(new_wa);
1232 return retval;
1235 else
1237 new_wa->backup = NULL;
1240 /* put new entry in list */
1241 *p = new_wa;
1244 /* mark as used, and return the new (reused) area */
1245 new_wa->free = false;
1246 *area = new_wa;
1248 /* user pointer */
1249 new_wa->user = area;
1251 return ERROR_OK;
1254 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1256 int retval;
1258 retval = target_alloc_working_area_try(target, size, area);
1259 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1261 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1263 return retval;
1267 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1269 if (area->free)
1270 return ERROR_OK;
1272 if (restore && target->backup_working_area)
1274 int retval;
1275 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1276 return retval;
1279 area->free = true;
1281 /* mark user pointer invalid */
1282 *area->user = NULL;
1283 area->user = NULL;
1285 return ERROR_OK;
1288 int target_free_working_area(struct target *target, struct working_area *area)
1290 return target_free_working_area_restore(target, area, 1);
1293 /* free resources and restore memory, if restoring memory fails,
1294 * free up resources anyway
1296 static void target_free_all_working_areas_restore(struct target *target, int restore)
1298 struct working_area *c = target->working_areas;
1300 while (c)
1302 struct working_area *next = c->next;
1303 target_free_working_area_restore(target, c, restore);
1305 if (c->backup)
1306 free(c->backup);
1308 free(c);
1310 c = next;
1313 target->working_areas = NULL;
1316 void target_free_all_working_areas(struct target *target)
1318 target_free_all_working_areas_restore(target, 1);
1321 int target_arch_state(struct target *target)
1323 int retval;
1324 if (target == NULL)
1326 LOG_USER("No target has been configured");
1327 return ERROR_OK;
1330 LOG_USER("target state: %s", target_state_name( target ));
1332 if (target->state != TARGET_HALTED)
1333 return ERROR_OK;
1335 retval = target->type->arch_state(target);
1336 return retval;
1339 /* Single aligned words are guaranteed to use 16 or 32 bit access
1340 * mode respectively, otherwise data is handled as quickly as
1341 * possible
1343 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1345 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1346 (int)size, (unsigned)address);
1348 if (!target_was_examined(target))
1350 LOG_ERROR("Target not examined yet");
1351 return ERROR_FAIL;
1354 if (size == 0) {
1355 return ERROR_OK;
1358 if ((address + size - 1) < address)
1360 /* GDB can request this when e.g. PC is 0xfffffffc*/
1361 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1362 (unsigned)address,
1363 (unsigned)size);
1364 return ERROR_FAIL;
1367 return target->type->write_buffer(target, address, size, buffer);
1370 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1372 int retval = ERROR_OK;
1374 if (((address % 2) == 0) && (size == 2))
1376 return target_write_memory(target, address, 2, 1, buffer);
1379 /* handle unaligned head bytes */
1380 if (address % 4)
1382 uint32_t unaligned = 4 - (address % 4);
1384 if (unaligned > size)
1385 unaligned = size;
1387 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1388 return retval;
1390 buffer += unaligned;
1391 address += unaligned;
1392 size -= unaligned;
1395 /* handle aligned words */
1396 if (size >= 4)
1398 int aligned = size - (size % 4);
1400 /* use bulk writes above a certain limit. This may have to be changed */
1401 if (aligned > 128)
1403 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1404 return retval;
1406 else
1408 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1409 return retval;
1412 buffer += aligned;
1413 address += aligned;
1414 size -= aligned;
1417 /* handle tail writes of less than 4 bytes */
1418 if (size > 0)
1420 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1421 return retval;
1424 return retval;
1427 /* Single aligned words are guaranteed to use 16 or 32 bit access
1428 * mode respectively, otherwise data is handled as quickly as
1429 * possible
1431 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1433 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1434 (int)size, (unsigned)address);
1436 if (!target_was_examined(target))
1438 LOG_ERROR("Target not examined yet");
1439 return ERROR_FAIL;
1442 if (size == 0) {
1443 return ERROR_OK;
1446 if ((address + size - 1) < address)
1448 /* GDB can request this when e.g. PC is 0xfffffffc*/
1449 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1450 address,
1451 size);
1452 return ERROR_FAIL;
1455 return target->type->read_buffer(target, address, size, buffer);
1458 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1460 int retval = ERROR_OK;
1462 if (((address % 2) == 0) && (size == 2))
1464 return target_read_memory(target, address, 2, 1, buffer);
1467 /* handle unaligned head bytes */
1468 if (address % 4)
1470 uint32_t unaligned = 4 - (address % 4);
1472 if (unaligned > size)
1473 unaligned = size;
1475 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1476 return retval;
1478 buffer += unaligned;
1479 address += unaligned;
1480 size -= unaligned;
1483 /* handle aligned words */
1484 if (size >= 4)
1486 int aligned = size - (size % 4);
1488 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1489 return retval;
1491 buffer += aligned;
1492 address += aligned;
1493 size -= aligned;
1496 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1497 if(size >=2)
1499 int aligned = size - (size%2);
1500 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1501 if (retval != ERROR_OK)
1502 return retval;
1504 buffer += aligned;
1505 address += aligned;
1506 size -= aligned;
1508 /* handle tail writes of less than 4 bytes */
1509 if (size > 0)
1511 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1512 return retval;
1515 return ERROR_OK;
1518 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1520 uint8_t *buffer;
1521 int retval;
1522 uint32_t i;
1523 uint32_t checksum = 0;
1524 if (!target_was_examined(target))
1526 LOG_ERROR("Target not examined yet");
1527 return ERROR_FAIL;
1530 if ((retval = target->type->checksum_memory(target, address,
1531 size, &checksum)) != ERROR_OK)
1533 buffer = malloc(size);
1534 if (buffer == NULL)
1536 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1537 return ERROR_INVALID_ARGUMENTS;
1539 retval = target_read_buffer(target, address, size, buffer);
1540 if (retval != ERROR_OK)
1542 free(buffer);
1543 return retval;
1546 /* convert to target endianness */
1547 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1549 uint32_t target_data;
1550 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1551 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1554 retval = image_calculate_checksum(buffer, size, &checksum);
1555 free(buffer);
1558 *crc = checksum;
1560 return retval;
1563 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1565 int retval;
1566 if (!target_was_examined(target))
1568 LOG_ERROR("Target not examined yet");
1569 return ERROR_FAIL;
1572 if (target->type->blank_check_memory == 0)
1573 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1575 retval = target->type->blank_check_memory(target, address, size, blank);
1577 return retval;
1580 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1582 uint8_t value_buf[4];
1583 if (!target_was_examined(target))
1585 LOG_ERROR("Target not examined yet");
1586 return ERROR_FAIL;
1589 int retval = target_read_memory(target, address, 4, 1, value_buf);
1591 if (retval == ERROR_OK)
1593 *value = target_buffer_get_u32(target, value_buf);
1594 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1595 address,
1596 *value);
1598 else
1600 *value = 0x0;
1601 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1602 address);
1605 return retval;
1608 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1610 uint8_t value_buf[2];
1611 if (!target_was_examined(target))
1613 LOG_ERROR("Target not examined yet");
1614 return ERROR_FAIL;
1617 int retval = target_read_memory(target, address, 2, 1, value_buf);
1619 if (retval == ERROR_OK)
1621 *value = target_buffer_get_u16(target, value_buf);
1622 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1623 address,
1624 *value);
1626 else
1628 *value = 0x0;
1629 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1630 address);
1633 return retval;
1636 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1638 int retval = target_read_memory(target, address, 1, 1, value);
1639 if (!target_was_examined(target))
1641 LOG_ERROR("Target not examined yet");
1642 return ERROR_FAIL;
1645 if (retval == ERROR_OK)
1647 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1648 address,
1649 *value);
1651 else
1653 *value = 0x0;
1654 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1655 address);
1658 return retval;
1661 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1663 int retval;
1664 uint8_t value_buf[4];
1665 if (!target_was_examined(target))
1667 LOG_ERROR("Target not examined yet");
1668 return ERROR_FAIL;
1671 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1672 address,
1673 value);
1675 target_buffer_set_u32(target, value_buf, value);
1676 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1678 LOG_DEBUG("failed: %i", retval);
1681 return retval;
1684 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1686 int retval;
1687 uint8_t value_buf[2];
1688 if (!target_was_examined(target))
1690 LOG_ERROR("Target not examined yet");
1691 return ERROR_FAIL;
1694 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1695 address,
1696 value);
1698 target_buffer_set_u16(target, value_buf, value);
1699 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1701 LOG_DEBUG("failed: %i", retval);
1704 return retval;
1707 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1709 int retval;
1710 if (!target_was_examined(target))
1712 LOG_ERROR("Target not examined yet");
1713 return ERROR_FAIL;
1716 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1717 address, value);
1719 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1721 LOG_DEBUG("failed: %i", retval);
1724 return retval;
1727 COMMAND_HANDLER(handle_targets_command)
1729 struct target *target = all_targets;
1731 if (CMD_ARGC == 1)
1733 target = get_target(CMD_ARGV[0]);
1734 if (target == NULL) {
1735 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1736 goto DumpTargets;
1738 if (!target->tap->enabled) {
1739 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1740 "can't be the current target\n",
1741 target->tap->dotted_name);
1742 return ERROR_FAIL;
1745 CMD_CTX->current_target = target->target_number;
1746 return ERROR_OK;
1748 DumpTargets:
1750 target = all_targets;
1751 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1752 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1753 while (target)
1755 const char *state;
1756 char marker = ' ';
1758 if (target->tap->enabled)
1759 state = target_state_name( target );
1760 else
1761 state = "tap-disabled";
1763 if (CMD_CTX->current_target == target->target_number)
1764 marker = '*';
1766 /* keep columns lined up to match the headers above */
1767 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1768 target->target_number,
1769 marker,
1770 target_name(target),
1771 target_type_name(target),
1772 Jim_Nvp_value2name_simple(nvp_target_endian,
1773 target->endianness)->name,
1774 target->tap->dotted_name,
1775 state);
1776 target = target->next;
1779 return ERROR_OK;
1782 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1784 static int powerDropout;
1785 static int srstAsserted;
1787 static int runPowerRestore;
1788 static int runPowerDropout;
1789 static int runSrstAsserted;
1790 static int runSrstDeasserted;
1792 static int sense_handler(void)
1794 static int prevSrstAsserted = 0;
1795 static int prevPowerdropout = 0;
1797 int retval;
1798 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1799 return retval;
1801 int powerRestored;
1802 powerRestored = prevPowerdropout && !powerDropout;
1803 if (powerRestored)
1805 runPowerRestore = 1;
1808 long long current = timeval_ms();
1809 static long long lastPower = 0;
1810 int waitMore = lastPower + 2000 > current;
1811 if (powerDropout && !waitMore)
1813 runPowerDropout = 1;
1814 lastPower = current;
1817 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1818 return retval;
1820 int srstDeasserted;
1821 srstDeasserted = prevSrstAsserted && !srstAsserted;
1823 static long long lastSrst = 0;
1824 waitMore = lastSrst + 2000 > current;
1825 if (srstDeasserted && !waitMore)
1827 runSrstDeasserted = 1;
1828 lastSrst = current;
1831 if (!prevSrstAsserted && srstAsserted)
1833 runSrstAsserted = 1;
1836 prevSrstAsserted = srstAsserted;
1837 prevPowerdropout = powerDropout;
1839 if (srstDeasserted || powerRestored)
1841 /* Other than logging the event we can't do anything here.
1842 * Issuing a reset is a particularly bad idea as we might
1843 * be inside a reset already.
1847 return ERROR_OK;
1850 static int backoff_times = 0;
1851 static int backoff_count = 0;
1853 /* process target state changes */
1854 static int handle_target(void *priv)
1856 Jim_Interp *interp = (Jim_Interp *)priv;
1857 int retval = ERROR_OK;
1859 if (!is_jtag_poll_safe())
1861 /* polling is disabled currently */
1862 return ERROR_OK;
1865 /* we do not want to recurse here... */
1866 static int recursive = 0;
1867 if (! recursive)
1869 recursive = 1;
1870 sense_handler();
1871 /* danger! running these procedures can trigger srst assertions and power dropouts.
1872 * We need to avoid an infinite loop/recursion here and we do that by
1873 * clearing the flags after running these events.
1875 int did_something = 0;
1876 if (runSrstAsserted)
1878 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1879 Jim_Eval(interp, "srst_asserted");
1880 did_something = 1;
1882 if (runSrstDeasserted)
1884 Jim_Eval(interp, "srst_deasserted");
1885 did_something = 1;
1887 if (runPowerDropout)
1889 LOG_INFO("Power dropout detected, running power_dropout proc.");
1890 Jim_Eval(interp, "power_dropout");
1891 did_something = 1;
1893 if (runPowerRestore)
1895 Jim_Eval(interp, "power_restore");
1896 did_something = 1;
1899 if (did_something)
1901 /* clear detect flags */
1902 sense_handler();
1905 /* clear action flags */
1907 runSrstAsserted = 0;
1908 runSrstDeasserted = 0;
1909 runPowerRestore = 0;
1910 runPowerDropout = 0;
1912 recursive = 0;
1915 if (backoff_times > backoff_count)
1917 /* do not poll this time as we failed previously */
1918 backoff_count++;
1919 return ERROR_OK;
1921 backoff_count = 0;
1923 /* Poll targets for state changes unless that's globally disabled.
1924 * Skip targets that are currently disabled.
1926 for (struct target *target = all_targets;
1927 is_jtag_poll_safe() && target;
1928 target = target->next)
1930 if (!target->tap->enabled)
1931 continue;
1933 /* only poll target if we've got power and srst isn't asserted */
1934 if (!powerDropout && !srstAsserted)
1936 /* polling may fail silently until the target has been examined */
1937 if ((retval = target_poll(target)) != ERROR_OK)
1939 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1940 if (backoff_times * polling_interval < 5000)
1942 backoff_times *= 2;
1943 backoff_times++;
1945 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1947 /* Tell GDB to halt the debugger. This allows the user to
1948 * run monitor commands to handle the situation.
1950 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1951 return retval;
1953 /* Since we succeeded, we reset backoff count */
1954 if (backoff_times > 0)
1956 LOG_USER("Polling succeeded again");
1958 backoff_times = 0;
1962 return retval;
1965 COMMAND_HANDLER(handle_reg_command)
1967 struct target *target;
1968 struct reg *reg = NULL;
1969 unsigned count = 0;
1970 char *value;
1972 LOG_DEBUG("-");
1974 target = get_current_target(CMD_CTX);
1976 /* list all available registers for the current target */
1977 if (CMD_ARGC == 0)
1979 struct reg_cache *cache = target->reg_cache;
1981 count = 0;
1982 while (cache)
1984 unsigned i;
1986 command_print(CMD_CTX, "===== %s", cache->name);
1988 for (i = 0, reg = cache->reg_list;
1989 i < cache->num_regs;
1990 i++, reg++, count++)
1992 /* only print cached values if they are valid */
1993 if (reg->valid) {
1994 value = buf_to_str(reg->value,
1995 reg->size, 16);
1996 command_print(CMD_CTX,
1997 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1998 count, reg->name,
1999 reg->size, value,
2000 reg->dirty
2001 ? " (dirty)"
2002 : "");
2003 free(value);
2004 } else {
2005 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2006 count, reg->name,
2007 reg->size) ;
2010 cache = cache->next;
2013 return ERROR_OK;
2016 /* access a single register by its ordinal number */
2017 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
2019 unsigned num;
2020 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2022 struct reg_cache *cache = target->reg_cache;
2023 count = 0;
2024 while (cache)
2026 unsigned i;
2027 for (i = 0; i < cache->num_regs; i++)
2029 if (count++ == num)
2031 reg = &cache->reg_list[i];
2032 break;
2035 if (reg)
2036 break;
2037 cache = cache->next;
2040 if (!reg)
2042 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2043 return ERROR_OK;
2045 } else /* access a single register by its name */
2047 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2049 if (!reg)
2051 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2052 return ERROR_OK;
2056 /* display a register */
2057 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2059 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2060 reg->valid = 0;
2062 if (reg->valid == 0)
2064 reg->type->get(reg);
2066 value = buf_to_str(reg->value, reg->size, 16);
2067 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2068 free(value);
2069 return ERROR_OK;
2072 /* set register value */
2073 if (CMD_ARGC == 2)
2075 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2076 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2078 reg->type->set(reg, buf);
2080 value = buf_to_str(reg->value, reg->size, 16);
2081 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2082 free(value);
2084 free(buf);
2086 return ERROR_OK;
2089 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2091 return ERROR_OK;
2094 COMMAND_HANDLER(handle_poll_command)
2096 int retval = ERROR_OK;
2097 struct target *target = get_current_target(CMD_CTX);
2099 if (CMD_ARGC == 0)
2101 command_print(CMD_CTX, "background polling: %s",
2102 jtag_poll_get_enabled() ? "on" : "off");
2103 command_print(CMD_CTX, "TAP: %s (%s)",
2104 target->tap->dotted_name,
2105 target->tap->enabled ? "enabled" : "disabled");
2106 if (!target->tap->enabled)
2107 return ERROR_OK;
2108 if ((retval = target_poll(target)) != ERROR_OK)
2109 return retval;
2110 if ((retval = target_arch_state(target)) != ERROR_OK)
2111 return retval;
2113 else if (CMD_ARGC == 1)
2115 bool enable;
2116 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2117 jtag_poll_set_enabled(enable);
2119 else
2121 return ERROR_COMMAND_SYNTAX_ERROR;
2124 return retval;
2127 COMMAND_HANDLER(handle_wait_halt_command)
2129 if (CMD_ARGC > 1)
2130 return ERROR_COMMAND_SYNTAX_ERROR;
2132 unsigned ms = 5000;
2133 if (1 == CMD_ARGC)
2135 int retval = parse_uint(CMD_ARGV[0], &ms);
2136 if (ERROR_OK != retval)
2138 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2139 return ERROR_COMMAND_SYNTAX_ERROR;
2141 // convert seconds (given) to milliseconds (needed)
2142 ms *= 1000;
2145 struct target *target = get_current_target(CMD_CTX);
2146 return target_wait_state(target, TARGET_HALTED, ms);
2149 /* wait for target state to change. The trick here is to have a low
2150 * latency for short waits and not to suck up all the CPU time
2151 * on longer waits.
2153 * After 500ms, keep_alive() is invoked
2155 int target_wait_state(struct target *target, enum target_state state, int ms)
2157 int retval;
2158 long long then = 0, cur;
2159 int once = 1;
2161 for (;;)
2163 if ((retval = target_poll(target)) != ERROR_OK)
2164 return retval;
2165 if (target->state == state)
2167 break;
2169 cur = timeval_ms();
2170 if (once)
2172 once = 0;
2173 then = timeval_ms();
2174 LOG_DEBUG("waiting for target %s...",
2175 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2178 if (cur-then > 500)
2180 keep_alive();
2183 if ((cur-then) > ms)
2185 LOG_ERROR("timed out while waiting for target %s",
2186 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2187 return ERROR_FAIL;
2191 return ERROR_OK;
2194 COMMAND_HANDLER(handle_halt_command)
2196 LOG_DEBUG("-");
2198 struct target *target = get_current_target(CMD_CTX);
2199 int retval = target_halt(target);
2200 if (ERROR_OK != retval)
2201 return retval;
2203 if (CMD_ARGC == 1)
2205 unsigned wait_local;
2206 retval = parse_uint(CMD_ARGV[0], &wait_local);
2207 if (ERROR_OK != retval)
2208 return ERROR_COMMAND_SYNTAX_ERROR;
2209 if (!wait_local)
2210 return ERROR_OK;
2213 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2216 COMMAND_HANDLER(handle_soft_reset_halt_command)
2218 struct target *target = get_current_target(CMD_CTX);
2220 LOG_USER("requesting target halt and executing a soft reset");
2222 target->type->soft_reset_halt(target);
2224 return ERROR_OK;
2227 COMMAND_HANDLER(handle_reset_command)
2229 if (CMD_ARGC > 1)
2230 return ERROR_COMMAND_SYNTAX_ERROR;
2232 enum target_reset_mode reset_mode = RESET_RUN;
2233 if (CMD_ARGC == 1)
2235 const Jim_Nvp *n;
2236 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2237 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2238 return ERROR_COMMAND_SYNTAX_ERROR;
2240 reset_mode = n->value;
2243 /* reset *all* targets */
2244 return target_process_reset(CMD_CTX, reset_mode);
2248 COMMAND_HANDLER(handle_resume_command)
2250 int current = 1;
2251 if (CMD_ARGC > 1)
2252 return ERROR_COMMAND_SYNTAX_ERROR;
2254 struct target *target = get_current_target(CMD_CTX);
2255 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2257 /* with no CMD_ARGV, resume from current pc, addr = 0,
2258 * with one arguments, addr = CMD_ARGV[0],
2259 * handle breakpoints, not debugging */
2260 uint32_t addr = 0;
2261 if (CMD_ARGC == 1)
2263 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2264 current = 0;
2267 return target_resume(target, current, addr, 1, 0);
2270 COMMAND_HANDLER(handle_step_command)
2272 if (CMD_ARGC > 1)
2273 return ERROR_COMMAND_SYNTAX_ERROR;
2275 LOG_DEBUG("-");
2277 /* with no CMD_ARGV, step from current pc, addr = 0,
2278 * with one argument addr = CMD_ARGV[0],
2279 * handle breakpoints, debugging */
2280 uint32_t addr = 0;
2281 int current_pc = 1;
2282 if (CMD_ARGC == 1)
2284 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2285 current_pc = 0;
2288 struct target *target = get_current_target(CMD_CTX);
2290 return target->type->step(target, current_pc, addr, 1);
2293 static void handle_md_output(struct command_context *cmd_ctx,
2294 struct target *target, uint32_t address, unsigned size,
2295 unsigned count, const uint8_t *buffer)
2297 const unsigned line_bytecnt = 32;
2298 unsigned line_modulo = line_bytecnt / size;
2300 char output[line_bytecnt * 4 + 1];
2301 unsigned output_len = 0;
2303 const char *value_fmt;
2304 switch (size) {
2305 case 4: value_fmt = "%8.8x "; break;
2306 case 2: value_fmt = "%4.4x "; break;
2307 case 1: value_fmt = "%2.2x "; break;
2308 default:
2309 /* "can't happen", caller checked */
2310 LOG_ERROR("invalid memory read size: %u", size);
2311 return;
2314 for (unsigned i = 0; i < count; i++)
2316 if (i % line_modulo == 0)
2318 output_len += snprintf(output + output_len,
2319 sizeof(output) - output_len,
2320 "0x%8.8x: ",
2321 (unsigned)(address + (i*size)));
2324 uint32_t value = 0;
2325 const uint8_t *value_ptr = buffer + i * size;
2326 switch (size) {
2327 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2328 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2329 case 1: value = *value_ptr;
2331 output_len += snprintf(output + output_len,
2332 sizeof(output) - output_len,
2333 value_fmt, value);
2335 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2337 command_print(cmd_ctx, "%s", output);
2338 output_len = 0;
2343 COMMAND_HANDLER(handle_md_command)
2345 if (CMD_ARGC < 1)
2346 return ERROR_COMMAND_SYNTAX_ERROR;
2348 unsigned size = 0;
2349 switch (CMD_NAME[2]) {
2350 case 'w': size = 4; break;
2351 case 'h': size = 2; break;
2352 case 'b': size = 1; break;
2353 default: return ERROR_COMMAND_SYNTAX_ERROR;
2356 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2357 int (*fn)(struct target *target,
2358 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2359 if (physical)
2361 CMD_ARGC--;
2362 CMD_ARGV++;
2363 fn=target_read_phys_memory;
2364 } else
2366 fn=target_read_memory;
2368 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2370 return ERROR_COMMAND_SYNTAX_ERROR;
2373 uint32_t address;
2374 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2376 unsigned count = 1;
2377 if (CMD_ARGC == 2)
2378 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2380 uint8_t *buffer = calloc(count, size);
2382 struct target *target = get_current_target(CMD_CTX);
2383 int retval = fn(target, address, size, count, buffer);
2384 if (ERROR_OK == retval)
2385 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2387 free(buffer);
2389 return retval;
2392 typedef int (*target_write_fn)(struct target *target,
2393 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2395 static int target_write_memory_fast(struct target *target,
2396 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2398 return target_write_buffer(target, address, size * count, buffer);
2401 static int target_fill_mem(struct target *target,
2402 uint32_t address,
2403 target_write_fn fn,
2404 unsigned data_size,
2405 /* value */
2406 uint32_t b,
2407 /* count */
2408 unsigned c)
2410 /* We have to write in reasonably large chunks to be able
2411 * to fill large memory areas with any sane speed */
2412 const unsigned chunk_size = 16384;
2413 uint8_t *target_buf = malloc(chunk_size * data_size);
2414 if (target_buf == NULL)
2416 LOG_ERROR("Out of memory");
2417 return ERROR_FAIL;
2420 for (unsigned i = 0; i < chunk_size; i ++)
2422 switch (data_size)
2424 case 4:
2425 target_buffer_set_u32(target, target_buf + i*data_size, b);
2426 break;
2427 case 2:
2428 target_buffer_set_u16(target, target_buf + i*data_size, b);
2429 break;
2430 case 1:
2431 target_buffer_set_u8(target, target_buf + i*data_size, b);
2432 break;
2433 default:
2434 exit(-1);
2438 int retval = ERROR_OK;
2440 for (unsigned x = 0; x < c; x += chunk_size)
2442 unsigned current;
2443 current = c - x;
2444 if (current > chunk_size)
2446 current = chunk_size;
2448 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2449 if (retval != ERROR_OK)
2451 break;
2453 /* avoid GDB timeouts */
2454 keep_alive();
2456 free(target_buf);
2458 return retval;
2462 COMMAND_HANDLER(handle_mw_command)
2464 if (CMD_ARGC < 2)
2466 return ERROR_COMMAND_SYNTAX_ERROR;
2468 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2469 target_write_fn fn;
2470 if (physical)
2472 CMD_ARGC--;
2473 CMD_ARGV++;
2474 fn=target_write_phys_memory;
2475 } else
2477 fn = target_write_memory_fast;
2479 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2480 return ERROR_COMMAND_SYNTAX_ERROR;
2482 uint32_t address;
2483 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2485 uint32_t value;
2486 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2488 unsigned count = 1;
2489 if (CMD_ARGC == 3)
2490 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2492 struct target *target = get_current_target(CMD_CTX);
2493 unsigned wordsize;
2494 switch (CMD_NAME[2])
2496 case 'w':
2497 wordsize = 4;
2498 break;
2499 case 'h':
2500 wordsize = 2;
2501 break;
2502 case 'b':
2503 wordsize = 1;
2504 break;
2505 default:
2506 return ERROR_COMMAND_SYNTAX_ERROR;
2509 return target_fill_mem(target, address, fn, wordsize, value, count);
2512 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2513 uint32_t *min_address, uint32_t *max_address)
2515 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2516 return ERROR_COMMAND_SYNTAX_ERROR;
2518 /* a base address isn't always necessary,
2519 * default to 0x0 (i.e. don't relocate) */
2520 if (CMD_ARGC >= 2)
2522 uint32_t addr;
2523 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2524 image->base_address = addr;
2525 image->base_address_set = 1;
2527 else
2528 image->base_address_set = 0;
2530 image->start_address_set = 0;
2532 if (CMD_ARGC >= 4)
2534 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2536 if (CMD_ARGC == 5)
2538 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2539 // use size (given) to find max (required)
2540 *max_address += *min_address;
2543 if (*min_address > *max_address)
2544 return ERROR_COMMAND_SYNTAX_ERROR;
2546 return ERROR_OK;
2549 COMMAND_HANDLER(handle_load_image_command)
2551 uint8_t *buffer;
2552 size_t buf_cnt;
2553 uint32_t image_size;
2554 uint32_t min_address = 0;
2555 uint32_t max_address = 0xffffffff;
2556 int i;
2557 struct image image;
2559 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2560 &image, &min_address, &max_address);
2561 if (ERROR_OK != retval)
2562 return retval;
2564 struct target *target = get_current_target(CMD_CTX);
2566 struct duration bench;
2567 duration_start(&bench);
2569 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2571 return ERROR_OK;
2574 image_size = 0x0;
2575 retval = ERROR_OK;
2576 for (i = 0; i < image.num_sections; i++)
2578 buffer = malloc(image.sections[i].size);
2579 if (buffer == NULL)
2581 command_print(CMD_CTX,
2582 "error allocating buffer for section (%d bytes)",
2583 (int)(image.sections[i].size));
2584 break;
2587 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2589 free(buffer);
2590 break;
2593 uint32_t offset = 0;
2594 uint32_t length = buf_cnt;
2596 /* DANGER!!! beware of unsigned comparision here!!! */
2598 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2599 (image.sections[i].base_address < max_address))
2601 if (image.sections[i].base_address < min_address)
2603 /* clip addresses below */
2604 offset += min_address-image.sections[i].base_address;
2605 length -= offset;
2608 if (image.sections[i].base_address + buf_cnt > max_address)
2610 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2613 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2615 free(buffer);
2616 break;
2618 image_size += length;
2619 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2620 (unsigned int)length,
2621 image.sections[i].base_address + offset);
2624 free(buffer);
2627 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2629 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2630 "in %fs (%0.3f KiB/s)", image_size,
2631 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2634 image_close(&image);
2636 return retval;
2640 COMMAND_HANDLER(handle_dump_image_command)
2642 struct fileio fileio;
2643 uint8_t buffer[560];
2644 int retval, retvaltemp;
2645 uint32_t address, size;
2646 struct duration bench;
2647 struct target *target = get_current_target(CMD_CTX);
2649 if (CMD_ARGC != 3)
2650 return ERROR_COMMAND_SYNTAX_ERROR;
2652 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2653 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2655 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2656 if (retval != ERROR_OK)
2657 return retval;
2659 duration_start(&bench);
2661 retval = ERROR_OK;
2662 while (size > 0)
2664 size_t size_written;
2665 uint32_t this_run_size = (size > 560) ? 560 : size;
2666 retval = target_read_buffer(target, address, this_run_size, buffer);
2667 if (retval != ERROR_OK)
2669 break;
2672 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2673 if (retval != ERROR_OK)
2675 break;
2678 size -= this_run_size;
2679 address += this_run_size;
2682 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2684 int filesize;
2685 retval = fileio_size(&fileio, &filesize);
2686 if (retval != ERROR_OK)
2687 return retval;
2688 command_print(CMD_CTX,
2689 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2690 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2693 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2694 return retvaltemp;
2696 return retval;
2699 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2701 uint8_t *buffer;
2702 size_t buf_cnt;
2703 uint32_t image_size;
2704 int i;
2705 int retval;
2706 uint32_t checksum = 0;
2707 uint32_t mem_checksum = 0;
2709 struct image image;
2711 struct target *target = get_current_target(CMD_CTX);
2713 if (CMD_ARGC < 1)
2715 return ERROR_COMMAND_SYNTAX_ERROR;
2718 if (!target)
2720 LOG_ERROR("no target selected");
2721 return ERROR_FAIL;
2724 struct duration bench;
2725 duration_start(&bench);
2727 if (CMD_ARGC >= 2)
2729 uint32_t addr;
2730 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2731 image.base_address = addr;
2732 image.base_address_set = 1;
2734 else
2736 image.base_address_set = 0;
2737 image.base_address = 0x0;
2740 image.start_address_set = 0;
2742 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2744 return retval;
2747 image_size = 0x0;
2748 int diffs = 0;
2749 retval = ERROR_OK;
2750 for (i = 0; i < image.num_sections; i++)
2752 buffer = malloc(image.sections[i].size);
2753 if (buffer == NULL)
2755 command_print(CMD_CTX,
2756 "error allocating buffer for section (%d bytes)",
2757 (int)(image.sections[i].size));
2758 break;
2760 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2762 free(buffer);
2763 break;
2766 if (verify)
2768 /* calculate checksum of image */
2769 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2770 if (retval != ERROR_OK)
2772 free(buffer);
2773 break;
2776 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2777 if (retval != ERROR_OK)
2779 free(buffer);
2780 break;
2783 if (checksum != mem_checksum)
2785 /* failed crc checksum, fall back to a binary compare */
2786 uint8_t *data;
2788 if (diffs == 0)
2790 LOG_ERROR("checksum mismatch - attempting binary compare");
2793 data = (uint8_t*)malloc(buf_cnt);
2795 /* Can we use 32bit word accesses? */
2796 int size = 1;
2797 int count = buf_cnt;
2798 if ((count % 4) == 0)
2800 size *= 4;
2801 count /= 4;
2803 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2804 if (retval == ERROR_OK)
2806 uint32_t t;
2807 for (t = 0; t < buf_cnt; t++)
2809 if (data[t] != buffer[t])
2811 command_print(CMD_CTX,
2812 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2813 diffs,
2814 (unsigned)(t + image.sections[i].base_address),
2815 data[t],
2816 buffer[t]);
2817 if (diffs++ >= 127)
2819 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2820 free(data);
2821 free(buffer);
2822 goto done;
2825 keep_alive();
2828 free(data);
2830 } else
2832 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2833 image.sections[i].base_address,
2834 buf_cnt);
2837 free(buffer);
2838 image_size += buf_cnt;
2840 if (diffs > 0)
2842 command_print(CMD_CTX, "No more differences found.");
2844 done:
2845 if (diffs > 0)
2847 retval = ERROR_FAIL;
2849 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2851 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2852 "in %fs (%0.3f KiB/s)", image_size,
2853 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2856 image_close(&image);
2858 return retval;
2861 COMMAND_HANDLER(handle_verify_image_command)
2863 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2866 COMMAND_HANDLER(handle_test_image_command)
2868 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2871 static int handle_bp_command_list(struct command_context *cmd_ctx)
2873 struct target *target = get_current_target(cmd_ctx);
2874 struct breakpoint *breakpoint = target->breakpoints;
2875 while (breakpoint)
2877 if (breakpoint->type == BKPT_SOFT)
2879 char* buf = buf_to_str(breakpoint->orig_instr,
2880 breakpoint->length, 16);
2881 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2882 breakpoint->address,
2883 breakpoint->length,
2884 breakpoint->set, buf);
2885 free(buf);
2887 else
2889 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2890 breakpoint->address,
2891 breakpoint->length, breakpoint->set);
2894 breakpoint = breakpoint->next;
2896 return ERROR_OK;
2899 static int handle_bp_command_set(struct command_context *cmd_ctx,
2900 uint32_t addr, uint32_t length, int hw)
2902 struct target *target = get_current_target(cmd_ctx);
2903 int retval = breakpoint_add(target, addr, length, hw);
2904 if (ERROR_OK == retval)
2905 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2906 else
2907 LOG_ERROR("Failure setting breakpoint");
2908 return retval;
2911 COMMAND_HANDLER(handle_bp_command)
2913 if (CMD_ARGC == 0)
2914 return handle_bp_command_list(CMD_CTX);
2916 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2918 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2919 return ERROR_COMMAND_SYNTAX_ERROR;
2922 uint32_t addr;
2923 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2924 uint32_t length;
2925 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2927 int hw = BKPT_SOFT;
2928 if (CMD_ARGC == 3)
2930 if (strcmp(CMD_ARGV[2], "hw") == 0)
2931 hw = BKPT_HARD;
2932 else
2933 return ERROR_COMMAND_SYNTAX_ERROR;
2936 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2939 COMMAND_HANDLER(handle_rbp_command)
2941 if (CMD_ARGC != 1)
2942 return ERROR_COMMAND_SYNTAX_ERROR;
2944 uint32_t addr;
2945 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2947 struct target *target = get_current_target(CMD_CTX);
2948 breakpoint_remove(target, addr);
2950 return ERROR_OK;
2953 COMMAND_HANDLER(handle_wp_command)
2955 struct target *target = get_current_target(CMD_CTX);
2957 if (CMD_ARGC == 0)
2959 struct watchpoint *watchpoint = target->watchpoints;
2961 while (watchpoint)
2963 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2964 ", len: 0x%8.8" PRIx32
2965 ", r/w/a: %i, value: 0x%8.8" PRIx32
2966 ", mask: 0x%8.8" PRIx32,
2967 watchpoint->address,
2968 watchpoint->length,
2969 (int)watchpoint->rw,
2970 watchpoint->value,
2971 watchpoint->mask);
2972 watchpoint = watchpoint->next;
2974 return ERROR_OK;
2977 enum watchpoint_rw type = WPT_ACCESS;
2978 uint32_t addr = 0;
2979 uint32_t length = 0;
2980 uint32_t data_value = 0x0;
2981 uint32_t data_mask = 0xffffffff;
2983 switch (CMD_ARGC)
2985 case 5:
2986 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2987 // fall through
2988 case 4:
2989 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2990 // fall through
2991 case 3:
2992 switch (CMD_ARGV[2][0])
2994 case 'r':
2995 type = WPT_READ;
2996 break;
2997 case 'w':
2998 type = WPT_WRITE;
2999 break;
3000 case 'a':
3001 type = WPT_ACCESS;
3002 break;
3003 default:
3004 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3005 return ERROR_COMMAND_SYNTAX_ERROR;
3007 // fall through
3008 case 2:
3009 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3010 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3011 break;
3013 default:
3014 command_print(CMD_CTX, "usage: wp [address length "
3015 "[(r|w|a) [value [mask]]]]");
3016 return ERROR_COMMAND_SYNTAX_ERROR;
3019 int retval = watchpoint_add(target, addr, length, type,
3020 data_value, data_mask);
3021 if (ERROR_OK != retval)
3022 LOG_ERROR("Failure setting watchpoints");
3024 return retval;
3027 COMMAND_HANDLER(handle_rwp_command)
3029 if (CMD_ARGC != 1)
3030 return ERROR_COMMAND_SYNTAX_ERROR;
3032 uint32_t addr;
3033 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3035 struct target *target = get_current_target(CMD_CTX);
3036 watchpoint_remove(target, addr);
3038 return ERROR_OK;
3043 * Translate a virtual address to a physical address.
3045 * The low-level target implementation must have logged a detailed error
3046 * which is forwarded to telnet/GDB session.
3048 COMMAND_HANDLER(handle_virt2phys_command)
3050 if (CMD_ARGC != 1)
3051 return ERROR_COMMAND_SYNTAX_ERROR;
3053 uint32_t va;
3054 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3055 uint32_t pa;
3057 struct target *target = get_current_target(CMD_CTX);
3058 int retval = target->type->virt2phys(target, va, &pa);
3059 if (retval == ERROR_OK)
3060 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3062 return retval;
3065 static void writeData(FILE *f, const void *data, size_t len)
3067 size_t written = fwrite(data, 1, len, f);
3068 if (written != len)
3069 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3072 static void writeLong(FILE *f, int l)
3074 int i;
3075 for (i = 0; i < 4; i++)
3077 char c = (l >> (i*8))&0xff;
3078 writeData(f, &c, 1);
3083 static void writeString(FILE *f, char *s)
3085 writeData(f, s, strlen(s));
3088 /* Dump a gmon.out histogram file. */
3089 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3091 uint32_t i;
3092 FILE *f = fopen(filename, "w");
3093 if (f == NULL)
3094 return;
3095 writeString(f, "gmon");
3096 writeLong(f, 0x00000001); /* Version */
3097 writeLong(f, 0); /* padding */
3098 writeLong(f, 0); /* padding */
3099 writeLong(f, 0); /* padding */
3101 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3102 writeData(f, &zero, 1);
3104 /* figure out bucket size */
3105 uint32_t min = samples[0];
3106 uint32_t max = samples[0];
3107 for (i = 0; i < sampleNum; i++)
3109 if (min > samples[i])
3111 min = samples[i];
3113 if (max < samples[i])
3115 max = samples[i];
3119 int addressSpace = (max-min + 1);
3121 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3122 uint32_t length = addressSpace;
3123 if (length > maxBuckets)
3125 length = maxBuckets;
3127 int *buckets = malloc(sizeof(int)*length);
3128 if (buckets == NULL)
3130 fclose(f);
3131 return;
3133 memset(buckets, 0, sizeof(int)*length);
3134 for (i = 0; i < sampleNum;i++)
3136 uint32_t address = samples[i];
3137 long long a = address-min;
3138 long long b = length-1;
3139 long long c = addressSpace-1;
3140 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3141 buckets[index_t]++;
3144 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3145 writeLong(f, min); /* low_pc */
3146 writeLong(f, max); /* high_pc */
3147 writeLong(f, length); /* # of samples */
3148 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3149 writeString(f, "seconds");
3150 for (i = 0; i < (15-strlen("seconds")); i++)
3151 writeData(f, &zero, 1);
3152 writeString(f, "s");
3154 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3156 char *data = malloc(2*length);
3157 if (data != NULL)
3159 for (i = 0; i < length;i++)
3161 int val;
3162 val = buckets[i];
3163 if (val > 65535)
3165 val = 65535;
3167 data[i*2]=val&0xff;
3168 data[i*2 + 1]=(val >> 8)&0xff;
3170 free(buckets);
3171 writeData(f, data, length * 2);
3172 free(data);
3173 } else
3175 free(buckets);
3178 fclose(f);
3181 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3182 * which will be used as a random sampling of PC */
3183 COMMAND_HANDLER(handle_profile_command)
3185 struct target *target = get_current_target(CMD_CTX);
3186 struct timeval timeout, now;
3188 gettimeofday(&timeout, NULL);
3189 if (CMD_ARGC != 2)
3191 return ERROR_COMMAND_SYNTAX_ERROR;
3193 unsigned offset;
3194 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3196 timeval_add_time(&timeout, offset, 0);
3199 * @todo: Some cores let us sample the PC without the
3200 * annoying halt/resume step; for example, ARMv7 PCSR.
3201 * Provide a way to use that more efficient mechanism.
3204 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3206 static const int maxSample = 10000;
3207 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3208 if (samples == NULL)
3209 return ERROR_OK;
3211 int numSamples = 0;
3212 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3213 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3215 for (;;)
3217 int retval;
3218 target_poll(target);
3219 if (target->state == TARGET_HALTED)
3221 uint32_t t=*((uint32_t *)reg->value);
3222 samples[numSamples++]=t;
3223 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3224 target_poll(target);
3225 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3226 } else if (target->state == TARGET_RUNNING)
3228 /* We want to quickly sample the PC. */
3229 if ((retval = target_halt(target)) != ERROR_OK)
3231 free(samples);
3232 return retval;
3234 } else
3236 command_print(CMD_CTX, "Target not halted or running");
3237 retval = ERROR_OK;
3238 break;
3240 if (retval != ERROR_OK)
3242 break;
3245 gettimeofday(&now, NULL);
3246 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3248 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3249 if ((retval = target_poll(target)) != ERROR_OK)
3251 free(samples);
3252 return retval;
3254 if (target->state == TARGET_HALTED)
3256 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3258 if ((retval = target_poll(target)) != ERROR_OK)
3260 free(samples);
3261 return retval;
3263 writeGmon(samples, numSamples, CMD_ARGV[1]);
3264 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3265 break;
3268 free(samples);
3270 return ERROR_OK;
3273 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3275 char *namebuf;
3276 Jim_Obj *nameObjPtr, *valObjPtr;
3277 int result;
3279 namebuf = alloc_printf("%s(%d)", varname, idx);
3280 if (!namebuf)
3281 return JIM_ERR;
3283 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3284 valObjPtr = Jim_NewIntObj(interp, val);
3285 if (!nameObjPtr || !valObjPtr)
3287 free(namebuf);
3288 return JIM_ERR;
3291 Jim_IncrRefCount(nameObjPtr);
3292 Jim_IncrRefCount(valObjPtr);
3293 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3294 Jim_DecrRefCount(interp, nameObjPtr);
3295 Jim_DecrRefCount(interp, valObjPtr);
3296 free(namebuf);
3297 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3298 return result;
3301 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3303 struct command_context *context;
3304 struct target *target;
3306 context = current_command_context(interp);
3307 assert (context != NULL);
3309 target = get_current_target(context);
3310 if (target == NULL)
3312 LOG_ERROR("mem2array: no current target");
3313 return JIM_ERR;
3316 return target_mem2array(interp, target, argc-1, argv + 1);
3319 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3321 long l;
3322 uint32_t width;
3323 int len;
3324 uint32_t addr;
3325 uint32_t count;
3326 uint32_t v;
3327 const char *varname;
3328 int n, e, retval;
3329 uint32_t i;
3331 /* argv[1] = name of array to receive the data
3332 * argv[2] = desired width
3333 * argv[3] = memory address
3334 * argv[4] = count of times to read
3336 if (argc != 4) {
3337 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3338 return JIM_ERR;
3340 varname = Jim_GetString(argv[0], &len);
3341 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3343 e = Jim_GetLong(interp, argv[1], &l);
3344 width = l;
3345 if (e != JIM_OK) {
3346 return e;
3349 e = Jim_GetLong(interp, argv[2], &l);
3350 addr = l;
3351 if (e != JIM_OK) {
3352 return e;
3354 e = Jim_GetLong(interp, argv[3], &l);
3355 len = l;
3356 if (e != JIM_OK) {
3357 return e;
3359 switch (width) {
3360 case 8:
3361 width = 1;
3362 break;
3363 case 16:
3364 width = 2;
3365 break;
3366 case 32:
3367 width = 4;
3368 break;
3369 default:
3370 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3371 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3372 return JIM_ERR;
3374 if (len == 0) {
3375 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3376 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3377 return JIM_ERR;
3379 if ((addr + (len * width)) < addr) {
3380 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3381 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3382 return JIM_ERR;
3384 /* absurd transfer size? */
3385 if (len > 65536) {
3386 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3387 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3388 return JIM_ERR;
3391 if ((width == 1) ||
3392 ((width == 2) && ((addr & 1) == 0)) ||
3393 ((width == 4) && ((addr & 3) == 0))) {
3394 /* all is well */
3395 } else {
3396 char buf[100];
3397 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3398 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3399 addr,
3400 width);
3401 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3402 return JIM_ERR;
3405 /* Transfer loop */
3407 /* index counter */
3408 n = 0;
3410 size_t buffersize = 4096;
3411 uint8_t *buffer = malloc(buffersize);
3412 if (buffer == NULL)
3413 return JIM_ERR;
3415 /* assume ok */
3416 e = JIM_OK;
3417 while (len) {
3418 /* Slurp... in buffer size chunks */
3420 count = len; /* in objects.. */
3421 if (count > (buffersize/width)) {
3422 count = (buffersize/width);
3425 retval = target_read_memory(target, addr, width, count, buffer);
3426 if (retval != ERROR_OK) {
3427 /* BOO !*/
3428 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3429 (unsigned int)addr,
3430 (int)width,
3431 (int)count);
3432 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3433 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3434 e = JIM_ERR;
3435 len = 0;
3436 } else {
3437 v = 0; /* shut up gcc */
3438 for (i = 0 ;i < count ;i++, n++) {
3439 switch (width) {
3440 case 4:
3441 v = target_buffer_get_u32(target, &buffer[i*width]);
3442 break;
3443 case 2:
3444 v = target_buffer_get_u16(target, &buffer[i*width]);
3445 break;
3446 case 1:
3447 v = buffer[i] & 0x0ff;
3448 break;
3450 new_int_array_element(interp, varname, n, v);
3452 len -= count;
3456 free(buffer);
3458 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3460 return JIM_OK;
3463 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3465 char *namebuf;
3466 Jim_Obj *nameObjPtr, *valObjPtr;
3467 int result;
3468 long l;
3470 namebuf = alloc_printf("%s(%d)", varname, idx);
3471 if (!namebuf)
3472 return JIM_ERR;
3474 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3475 if (!nameObjPtr)
3477 free(namebuf);
3478 return JIM_ERR;
3481 Jim_IncrRefCount(nameObjPtr);
3482 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3483 Jim_DecrRefCount(interp, nameObjPtr);
3484 free(namebuf);
3485 if (valObjPtr == NULL)
3486 return JIM_ERR;
3488 result = Jim_GetLong(interp, valObjPtr, &l);
3489 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3490 *val = l;
3491 return result;
3494 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3496 struct command_context *context;
3497 struct target *target;
3499 context = current_command_context(interp);
3500 assert (context != NULL);
3502 target = get_current_target(context);
3503 if (target == NULL) {
3504 LOG_ERROR("array2mem: no current target");
3505 return JIM_ERR;
3508 return target_array2mem(interp,target, argc-1, argv + 1);
3511 static int target_array2mem(Jim_Interp *interp, struct target *target,
3512 int argc, Jim_Obj *const *argv)
3514 long l;
3515 uint32_t width;
3516 int len;
3517 uint32_t addr;
3518 uint32_t count;
3519 uint32_t v;
3520 const char *varname;
3521 int n, e, retval;
3522 uint32_t i;
3524 /* argv[1] = name of array to get the data
3525 * argv[2] = desired width
3526 * argv[3] = memory address
3527 * argv[4] = count to write
3529 if (argc != 4) {
3530 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3531 return JIM_ERR;
3533 varname = Jim_GetString(argv[0], &len);
3534 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3536 e = Jim_GetLong(interp, argv[1], &l);
3537 width = l;
3538 if (e != JIM_OK) {
3539 return e;
3542 e = Jim_GetLong(interp, argv[2], &l);
3543 addr = l;
3544 if (e != JIM_OK) {
3545 return e;
3547 e = Jim_GetLong(interp, argv[3], &l);
3548 len = l;
3549 if (e != JIM_OK) {
3550 return e;
3552 switch (width) {
3553 case 8:
3554 width = 1;
3555 break;
3556 case 16:
3557 width = 2;
3558 break;
3559 case 32:
3560 width = 4;
3561 break;
3562 default:
3563 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3564 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3565 return JIM_ERR;
3567 if (len == 0) {
3568 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3569 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3570 return JIM_ERR;
3572 if ((addr + (len * width)) < addr) {
3573 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3574 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3575 return JIM_ERR;
3577 /* absurd transfer size? */
3578 if (len > 65536) {
3579 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3580 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3581 return JIM_ERR;
3584 if ((width == 1) ||
3585 ((width == 2) && ((addr & 1) == 0)) ||
3586 ((width == 4) && ((addr & 3) == 0))) {
3587 /* all is well */
3588 } else {
3589 char buf[100];
3590 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3591 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3592 (unsigned int)addr,
3593 (int)width);
3594 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3595 return JIM_ERR;
3598 /* Transfer loop */
3600 /* index counter */
3601 n = 0;
3602 /* assume ok */
3603 e = JIM_OK;
3605 size_t buffersize = 4096;
3606 uint8_t *buffer = malloc(buffersize);
3607 if (buffer == NULL)
3608 return JIM_ERR;
3610 while (len) {
3611 /* Slurp... in buffer size chunks */
3613 count = len; /* in objects.. */
3614 if (count > (buffersize/width)) {
3615 count = (buffersize/width);
3618 v = 0; /* shut up gcc */
3619 for (i = 0 ;i < count ;i++, n++) {
3620 get_int_array_element(interp, varname, n, &v);
3621 switch (width) {
3622 case 4:
3623 target_buffer_set_u32(target, &buffer[i*width], v);
3624 break;
3625 case 2:
3626 target_buffer_set_u16(target, &buffer[i*width], v);
3627 break;
3628 case 1:
3629 buffer[i] = v & 0x0ff;
3630 break;
3633 len -= count;
3635 retval = target_write_memory(target, addr, width, count, buffer);
3636 if (retval != ERROR_OK) {
3637 /* BOO !*/
3638 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3639 (unsigned int)addr,
3640 (int)width,
3641 (int)count);
3642 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3643 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3644 e = JIM_ERR;
3645 len = 0;
3649 free(buffer);
3651 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3653 return JIM_OK;
3656 /* FIX? should we propagate errors here rather than printing them
3657 * and continuing?
3659 void target_handle_event(struct target *target, enum target_event e)
3661 struct target_event_action *teap;
3663 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3664 if (teap->event == e) {
3665 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3666 target->target_number,
3667 target_name(target),
3668 target_type_name(target),
3670 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3671 Jim_GetString(teap->body, NULL));
3672 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3674 Jim_MakeErrorMessage(teap->interp);
3675 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3682 * Returns true only if the target has a handler for the specified event.
3684 bool target_has_event_action(struct target *target, enum target_event event)
3686 struct target_event_action *teap;
3688 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3689 if (teap->event == event)
3690 return true;
3692 return false;
3695 enum target_cfg_param {
3696 TCFG_TYPE,
3697 TCFG_EVENT,
3698 TCFG_WORK_AREA_VIRT,
3699 TCFG_WORK_AREA_PHYS,
3700 TCFG_WORK_AREA_SIZE,
3701 TCFG_WORK_AREA_BACKUP,
3702 TCFG_ENDIAN,
3703 TCFG_VARIANT,
3704 TCFG_COREID,
3705 TCFG_CHAIN_POSITION,
3706 TCFG_DBGBASE,
3709 static Jim_Nvp nvp_config_opts[] = {
3710 { .name = "-type", .value = TCFG_TYPE },
3711 { .name = "-event", .value = TCFG_EVENT },
3712 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3713 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3714 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3715 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3716 { .name = "-endian" , .value = TCFG_ENDIAN },
3717 { .name = "-variant", .value = TCFG_VARIANT },
3718 { .name = "-coreid", .value = TCFG_COREID },
3719 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3720 { .name = "-dbgbase", .value = TCFG_DBGBASE },
3721 { .name = NULL, .value = -1 }
3724 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3726 Jim_Nvp *n;
3727 Jim_Obj *o;
3728 jim_wide w;
3729 char *cp;
3730 int e;
3732 /* parse config or cget options ... */
3733 while (goi->argc > 0) {
3734 Jim_SetEmptyResult(goi->interp);
3735 /* Jim_GetOpt_Debug(goi); */
3737 if (target->type->target_jim_configure) {
3738 /* target defines a configure function */
3739 /* target gets first dibs on parameters */
3740 e = (*(target->type->target_jim_configure))(target, goi);
3741 if (e == JIM_OK) {
3742 /* more? */
3743 continue;
3745 if (e == JIM_ERR) {
3746 /* An error */
3747 return e;
3749 /* otherwise we 'continue' below */
3751 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3752 if (e != JIM_OK) {
3753 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3754 return e;
3756 switch (n->value) {
3757 case TCFG_TYPE:
3758 /* not setable */
3759 if (goi->isconfigure) {
3760 Jim_SetResultFormatted(goi->interp,
3761 "not settable: %s", n->name);
3762 return JIM_ERR;
3763 } else {
3764 no_params:
3765 if (goi->argc != 0) {
3766 Jim_WrongNumArgs(goi->interp,
3767 goi->argc, goi->argv,
3768 "NO PARAMS");
3769 return JIM_ERR;
3772 Jim_SetResultString(goi->interp,
3773 target_type_name(target), -1);
3774 /* loop for more */
3775 break;
3776 case TCFG_EVENT:
3777 if (goi->argc == 0) {
3778 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3779 return JIM_ERR;
3782 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3783 if (e != JIM_OK) {
3784 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3785 return e;
3788 if (goi->isconfigure) {
3789 if (goi->argc != 1) {
3790 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3791 return JIM_ERR;
3793 } else {
3794 if (goi->argc != 0) {
3795 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3796 return JIM_ERR;
3801 struct target_event_action *teap;
3803 teap = target->event_action;
3804 /* replace existing? */
3805 while (teap) {
3806 if (teap->event == (enum target_event)n->value) {
3807 break;
3809 teap = teap->next;
3812 if (goi->isconfigure) {
3813 bool replace = true;
3814 if (teap == NULL) {
3815 /* create new */
3816 teap = calloc(1, sizeof(*teap));
3817 replace = false;
3819 teap->event = n->value;
3820 teap->interp = goi->interp;
3821 Jim_GetOpt_Obj(goi, &o);
3822 if (teap->body) {
3823 Jim_DecrRefCount(teap->interp, teap->body);
3825 teap->body = Jim_DuplicateObj(goi->interp, o);
3827 * FIXME:
3828 * Tcl/TK - "tk events" have a nice feature.
3829 * See the "BIND" command.
3830 * We should support that here.
3831 * You can specify %X and %Y in the event code.
3832 * The idea is: %T - target name.
3833 * The idea is: %N - target number
3834 * The idea is: %E - event name.
3836 Jim_IncrRefCount(teap->body);
3838 if (!replace)
3840 /* add to head of event list */
3841 teap->next = target->event_action;
3842 target->event_action = teap;
3844 Jim_SetEmptyResult(goi->interp);
3845 } else {
3846 /* get */
3847 if (teap == NULL) {
3848 Jim_SetEmptyResult(goi->interp);
3849 } else {
3850 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3854 /* loop for more */
3855 break;
3857 case TCFG_WORK_AREA_VIRT:
3858 if (goi->isconfigure) {
3859 target_free_all_working_areas(target);
3860 e = Jim_GetOpt_Wide(goi, &w);
3861 if (e != JIM_OK) {
3862 return e;
3864 target->working_area_virt = w;
3865 target->working_area_virt_spec = true;
3866 } else {
3867 if (goi->argc != 0) {
3868 goto no_params;
3871 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3872 /* loop for more */
3873 break;
3875 case TCFG_WORK_AREA_PHYS:
3876 if (goi->isconfigure) {
3877 target_free_all_working_areas(target);
3878 e = Jim_GetOpt_Wide(goi, &w);
3879 if (e != JIM_OK) {
3880 return e;
3882 target->working_area_phys = w;
3883 target->working_area_phys_spec = true;
3884 } else {
3885 if (goi->argc != 0) {
3886 goto no_params;
3889 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3890 /* loop for more */
3891 break;
3893 case TCFG_WORK_AREA_SIZE:
3894 if (goi->isconfigure) {
3895 target_free_all_working_areas(target);
3896 e = Jim_GetOpt_Wide(goi, &w);
3897 if (e != JIM_OK) {
3898 return e;
3900 target->working_area_size = w;
3901 } else {
3902 if (goi->argc != 0) {
3903 goto no_params;
3906 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3907 /* loop for more */
3908 break;
3910 case TCFG_WORK_AREA_BACKUP:
3911 if (goi->isconfigure) {
3912 target_free_all_working_areas(target);
3913 e = Jim_GetOpt_Wide(goi, &w);
3914 if (e != JIM_OK) {
3915 return e;
3917 /* make this exactly 1 or 0 */
3918 target->backup_working_area = (!!w);
3919 } else {
3920 if (goi->argc != 0) {
3921 goto no_params;
3924 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3925 /* loop for more e*/
3926 break;
3928 case TCFG_ENDIAN:
3929 if (goi->isconfigure) {
3930 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3931 if (e != JIM_OK) {
3932 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3933 return e;
3935 target->endianness = n->value;
3936 } else {
3937 if (goi->argc != 0) {
3938 goto no_params;
3941 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3942 if (n->name == NULL) {
3943 target->endianness = TARGET_LITTLE_ENDIAN;
3944 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3946 Jim_SetResultString(goi->interp, n->name, -1);
3947 /* loop for more */
3948 break;
3950 case TCFG_VARIANT:
3951 if (goi->isconfigure) {
3952 if (goi->argc < 1) {
3953 Jim_SetResultFormatted(goi->interp,
3954 "%s ?STRING?",
3955 n->name);
3956 return JIM_ERR;
3958 if (target->variant) {
3959 free((void *)(target->variant));
3961 e = Jim_GetOpt_String(goi, &cp, NULL);
3962 target->variant = strdup(cp);
3963 } else {
3964 if (goi->argc != 0) {
3965 goto no_params;
3968 Jim_SetResultString(goi->interp, target->variant,-1);
3969 /* loop for more */
3970 break;
3972 case TCFG_COREID:
3973 if (goi->isconfigure) {
3974 e = Jim_GetOpt_Wide(goi, &w);
3975 if (e != JIM_OK) {
3976 return e;
3978 target->coreid = (int)w;
3979 } else {
3980 if (goi->argc != 0) {
3981 goto no_params;
3984 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3985 /* loop for more */
3986 break;
3988 case TCFG_CHAIN_POSITION:
3989 if (goi->isconfigure) {
3990 Jim_Obj *o_t;
3991 struct jtag_tap *tap;
3992 target_free_all_working_areas(target);
3993 e = Jim_GetOpt_Obj(goi, &o_t);
3994 if (e != JIM_OK) {
3995 return e;
3997 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
3998 if (tap == NULL) {
3999 return JIM_ERR;
4001 /* make this exactly 1 or 0 */
4002 target->tap = tap;
4003 } else {
4004 if (goi->argc != 0) {
4005 goto no_params;
4008 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4009 /* loop for more e*/
4010 break;
4011 case TCFG_DBGBASE:
4012 if (goi->isconfigure) {
4013 e = Jim_GetOpt_Wide(goi, &w);
4014 if (e != JIM_OK) {
4015 return e;
4017 target->dbgbase = (uint32_t)w;
4018 target->dbgbase_set = true;
4019 } else {
4020 if (goi->argc != 0) {
4021 goto no_params;
4024 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4025 /* loop for more */
4026 break;
4028 } /* while (goi->argc) */
4031 /* done - we return */
4032 return JIM_OK;
4035 static int
4036 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4038 Jim_GetOptInfo goi;
4040 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4041 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4042 int need_args = 1 + goi.isconfigure;
4043 if (goi.argc < need_args)
4045 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4046 goi.isconfigure
4047 ? "missing: -option VALUE ..."
4048 : "missing: -option ...");
4049 return JIM_ERR;
4051 struct target *target = Jim_CmdPrivData(goi.interp);
4052 return target_configure(&goi, target);
4055 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4057 const char *cmd_name = Jim_GetString(argv[0], NULL);
4059 Jim_GetOptInfo goi;
4060 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4062 if (goi.argc < 2 || goi.argc > 4)
4064 Jim_SetResultFormatted(goi.interp,
4065 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4066 return JIM_ERR;
4069 target_write_fn fn;
4070 fn = target_write_memory_fast;
4072 int e;
4073 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4075 /* consume it */
4076 struct Jim_Obj *obj;
4077 e = Jim_GetOpt_Obj(&goi, &obj);
4078 if (e != JIM_OK)
4079 return e;
4081 fn = target_write_phys_memory;
4084 jim_wide a;
4085 e = Jim_GetOpt_Wide(&goi, &a);
4086 if (e != JIM_OK)
4087 return e;
4089 jim_wide b;
4090 e = Jim_GetOpt_Wide(&goi, &b);
4091 if (e != JIM_OK)
4092 return e;
4094 jim_wide c = 1;
4095 if (goi.argc == 1)
4097 e = Jim_GetOpt_Wide(&goi, &c);
4098 if (e != JIM_OK)
4099 return e;
4102 /* all args must be consumed */
4103 if (goi.argc != 0)
4105 return JIM_ERR;
4108 struct target *target = Jim_CmdPrivData(goi.interp);
4109 unsigned data_size;
4110 if (strcasecmp(cmd_name, "mww") == 0) {
4111 data_size = 4;
4113 else if (strcasecmp(cmd_name, "mwh") == 0) {
4114 data_size = 2;
4116 else if (strcasecmp(cmd_name, "mwb") == 0) {
4117 data_size = 1;
4118 } else {
4119 LOG_ERROR("command '%s' unknown: ", cmd_name);
4120 return JIM_ERR;
4123 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4126 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4128 const char *cmd_name = Jim_GetString(argv[0], NULL);
4130 Jim_GetOptInfo goi;
4131 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4133 if ((goi.argc < 1) || (goi.argc > 3))
4135 Jim_SetResultFormatted(goi.interp,
4136 "usage: %s [phys] <address> [<count>]", cmd_name);
4137 return JIM_ERR;
4140 int (*fn)(struct target *target,
4141 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4142 fn=target_read_memory;
4144 int e;
4145 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4147 /* consume it */
4148 struct Jim_Obj *obj;
4149 e = Jim_GetOpt_Obj(&goi, &obj);
4150 if (e != JIM_OK)
4151 return e;
4153 fn=target_read_phys_memory;
4156 jim_wide a;
4157 e = Jim_GetOpt_Wide(&goi, &a);
4158 if (e != JIM_OK) {
4159 return JIM_ERR;
4161 jim_wide c;
4162 if (goi.argc == 1) {
4163 e = Jim_GetOpt_Wide(&goi, &c);
4164 if (e != JIM_OK) {
4165 return JIM_ERR;
4167 } else {
4168 c = 1;
4171 /* all args must be consumed */
4172 if (goi.argc != 0)
4174 return JIM_ERR;
4177 jim_wide b = 1; /* shut up gcc */
4178 if (strcasecmp(cmd_name, "mdw") == 0)
4179 b = 4;
4180 else if (strcasecmp(cmd_name, "mdh") == 0)
4181 b = 2;
4182 else if (strcasecmp(cmd_name, "mdb") == 0)
4183 b = 1;
4184 else {
4185 LOG_ERROR("command '%s' unknown: ", cmd_name);
4186 return JIM_ERR;
4189 /* convert count to "bytes" */
4190 c = c * b;
4192 struct target *target = Jim_CmdPrivData(goi.interp);
4193 uint8_t target_buf[32];
4194 jim_wide x, y, z;
4195 while (c > 0) {
4196 y = c;
4197 if (y > 16) {
4198 y = 16;
4200 e = fn(target, a, b, y / b, target_buf);
4201 if (e != ERROR_OK) {
4202 char tmp[10];
4203 snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4204 Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4205 return JIM_ERR;
4208 command_print(NULL, "0x%08x ", (int)(a));
4209 switch (b) {
4210 case 4:
4211 for (x = 0; x < 16 && x < y; x += 4)
4213 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4214 command_print(NULL, "%08x ", (int)(z));
4216 for (; (x < 16) ; x += 4) {
4217 command_print(NULL, " ");
4219 break;
4220 case 2:
4221 for (x = 0; x < 16 && x < y; x += 2)
4223 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4224 command_print(NULL, "%04x ", (int)(z));
4226 for (; (x < 16) ; x += 2) {
4227 command_print(NULL, " ");
4229 break;
4230 case 1:
4231 default:
4232 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4233 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4234 command_print(NULL, "%02x ", (int)(z));
4236 for (; (x < 16) ; x += 1) {
4237 command_print(NULL, " ");
4239 break;
4241 /* ascii-ify the bytes */
4242 for (x = 0 ; x < y ; x++) {
4243 if ((target_buf[x] >= 0x20) &&
4244 (target_buf[x] <= 0x7e)) {
4245 /* good */
4246 } else {
4247 /* smack it */
4248 target_buf[x] = '.';
4251 /* space pad */
4252 while (x < 16) {
4253 target_buf[x] = ' ';
4254 x++;
4256 /* terminate */
4257 target_buf[16] = 0;
4258 /* print - with a newline */
4259 command_print(NULL, "%s\n", target_buf);
4260 /* NEXT... */
4261 c -= 16;
4262 a += 16;
4264 return JIM_OK;
4267 static int jim_target_mem2array(Jim_Interp *interp,
4268 int argc, Jim_Obj *const *argv)
4270 struct target *target = Jim_CmdPrivData(interp);
4271 return target_mem2array(interp, target, argc - 1, argv + 1);
4274 static int jim_target_array2mem(Jim_Interp *interp,
4275 int argc, Jim_Obj *const *argv)
4277 struct target *target = Jim_CmdPrivData(interp);
4278 return target_array2mem(interp, target, argc - 1, argv + 1);
4281 static int jim_target_tap_disabled(Jim_Interp *interp)
4283 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4284 return JIM_ERR;
4287 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4289 if (argc != 1)
4291 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4292 return JIM_ERR;
4294 struct target *target = Jim_CmdPrivData(interp);
4295 if (!target->tap->enabled)
4296 return jim_target_tap_disabled(interp);
4298 int e = target->type->examine(target);
4299 if (e != ERROR_OK)
4301 return JIM_ERR;
4303 return JIM_OK;
4306 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4308 if (argc != 1)
4310 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4311 return JIM_ERR;
4313 struct target *target = Jim_CmdPrivData(interp);
4315 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4316 return JIM_ERR;
4318 return JIM_OK;
4321 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4323 if (argc != 1)
4325 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4326 return JIM_ERR;
4328 struct target *target = Jim_CmdPrivData(interp);
4329 if (!target->tap->enabled)
4330 return jim_target_tap_disabled(interp);
4332 int e;
4333 if (!(target_was_examined(target))) {
4334 e = ERROR_TARGET_NOT_EXAMINED;
4335 } else {
4336 e = target->type->poll(target);
4338 if (e != ERROR_OK)
4340 return JIM_ERR;
4342 return JIM_OK;
4345 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4347 Jim_GetOptInfo goi;
4348 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4350 if (goi.argc != 2)
4352 Jim_WrongNumArgs(interp, 0, argv,
4353 "([tT]|[fF]|assert|deassert) BOOL");
4354 return JIM_ERR;
4357 Jim_Nvp *n;
4358 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4359 if (e != JIM_OK)
4361 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4362 return e;
4364 /* the halt or not param */
4365 jim_wide a;
4366 e = Jim_GetOpt_Wide(&goi, &a);
4367 if (e != JIM_OK)
4368 return e;
4370 struct target *target = Jim_CmdPrivData(goi.interp);
4371 if (!target->tap->enabled)
4372 return jim_target_tap_disabled(interp);
4373 if (!(target_was_examined(target)))
4375 LOG_ERROR("Target not examined yet");
4376 return ERROR_TARGET_NOT_EXAMINED;
4378 if (!target->type->assert_reset || !target->type->deassert_reset)
4380 Jim_SetResultFormatted(interp,
4381 "No target-specific reset for %s",
4382 target_name(target));
4383 return JIM_ERR;
4385 /* determine if we should halt or not. */
4386 target->reset_halt = !!a;
4387 /* When this happens - all workareas are invalid. */
4388 target_free_all_working_areas_restore(target, 0);
4390 /* do the assert */
4391 if (n->value == NVP_ASSERT) {
4392 e = target->type->assert_reset(target);
4393 } else {
4394 e = target->type->deassert_reset(target);
4396 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4399 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4401 if (argc != 1) {
4402 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4403 return JIM_ERR;
4405 struct target *target = Jim_CmdPrivData(interp);
4406 if (!target->tap->enabled)
4407 return jim_target_tap_disabled(interp);
4408 int e = target->type->halt(target);
4409 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4412 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4414 Jim_GetOptInfo goi;
4415 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4417 /* params: <name> statename timeoutmsecs */
4418 if (goi.argc != 2)
4420 const char *cmd_name = Jim_GetString(argv[0], NULL);
4421 Jim_SetResultFormatted(goi.interp,
4422 "%s <state_name> <timeout_in_msec>", cmd_name);
4423 return JIM_ERR;
4426 Jim_Nvp *n;
4427 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4428 if (e != JIM_OK) {
4429 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4430 return e;
4432 jim_wide a;
4433 e = Jim_GetOpt_Wide(&goi, &a);
4434 if (e != JIM_OK) {
4435 return e;
4437 struct target *target = Jim_CmdPrivData(interp);
4438 if (!target->tap->enabled)
4439 return jim_target_tap_disabled(interp);
4441 e = target_wait_state(target, n->value, a);
4442 if (e != ERROR_OK)
4444 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4445 Jim_SetResultFormatted(goi.interp,
4446 "target: %s wait %s fails (%#s) %s",
4447 target_name(target), n->name,
4448 eObj, target_strerror_safe(e));
4449 Jim_FreeNewObj(interp, eObj);
4450 return JIM_ERR;
4452 return JIM_OK;
4454 /* List for human, Events defined for this target.
4455 * scripts/programs should use 'name cget -event NAME'
4457 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4459 struct command_context *cmd_ctx = current_command_context(interp);
4460 assert (cmd_ctx != NULL);
4462 struct target *target = Jim_CmdPrivData(interp);
4463 struct target_event_action *teap = target->event_action;
4464 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4465 target->target_number,
4466 target_name(target));
4467 command_print(cmd_ctx, "%-25s | Body", "Event");
4468 command_print(cmd_ctx, "------------------------- | "
4469 "----------------------------------------");
4470 while (teap)
4472 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4473 command_print(cmd_ctx, "%-25s | %s",
4474 opt->name, Jim_GetString(teap->body, NULL));
4475 teap = teap->next;
4477 command_print(cmd_ctx, "***END***");
4478 return JIM_OK;
4480 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4482 if (argc != 1)
4484 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4485 return JIM_ERR;
4487 struct target *target = Jim_CmdPrivData(interp);
4488 Jim_SetResultString(interp, target_state_name(target), -1);
4489 return JIM_OK;
4491 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4493 Jim_GetOptInfo goi;
4494 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4495 if (goi.argc != 1)
4497 const char *cmd_name = Jim_GetString(argv[0], NULL);
4498 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4499 return JIM_ERR;
4501 Jim_Nvp *n;
4502 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4503 if (e != JIM_OK)
4505 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4506 return e;
4508 struct target *target = Jim_CmdPrivData(interp);
4509 target_handle_event(target, n->value);
4510 return JIM_OK;
4513 static const struct command_registration target_instance_command_handlers[] = {
4515 .name = "configure",
4516 .mode = COMMAND_CONFIG,
4517 .jim_handler = jim_target_configure,
4518 .help = "configure a new target for use",
4519 .usage = "[target_attribute ...]",
4522 .name = "cget",
4523 .mode = COMMAND_ANY,
4524 .jim_handler = jim_target_configure,
4525 .help = "returns the specified target attribute",
4526 .usage = "target_attribute",
4529 .name = "mww",
4530 .mode = COMMAND_EXEC,
4531 .jim_handler = jim_target_mw,
4532 .help = "Write 32-bit word(s) to target memory",
4533 .usage = "address data [count]",
4536 .name = "mwh",
4537 .mode = COMMAND_EXEC,
4538 .jim_handler = jim_target_mw,
4539 .help = "Write 16-bit half-word(s) to target memory",
4540 .usage = "address data [count]",
4543 .name = "mwb",
4544 .mode = COMMAND_EXEC,
4545 .jim_handler = jim_target_mw,
4546 .help = "Write byte(s) to target memory",
4547 .usage = "address data [count]",
4550 .name = "mdw",
4551 .mode = COMMAND_EXEC,
4552 .jim_handler = jim_target_md,
4553 .help = "Display target memory as 32-bit words",
4554 .usage = "address [count]",
4557 .name = "mdh",
4558 .mode = COMMAND_EXEC,
4559 .jim_handler = jim_target_md,
4560 .help = "Display target memory as 16-bit half-words",
4561 .usage = "address [count]",
4564 .name = "mdb",
4565 .mode = COMMAND_EXEC,
4566 .jim_handler = jim_target_md,
4567 .help = "Display target memory as 8-bit bytes",
4568 .usage = "address [count]",
4571 .name = "array2mem",
4572 .mode = COMMAND_EXEC,
4573 .jim_handler = jim_target_array2mem,
4574 .help = "Writes Tcl array of 8/16/32 bit numbers "
4575 "to target memory",
4576 .usage = "arrayname bitwidth address count",
4579 .name = "mem2array",
4580 .mode = COMMAND_EXEC,
4581 .jim_handler = jim_target_mem2array,
4582 .help = "Loads Tcl array of 8/16/32 bit numbers "
4583 "from target memory",
4584 .usage = "arrayname bitwidth address count",
4587 .name = "eventlist",
4588 .mode = COMMAND_EXEC,
4589 .jim_handler = jim_target_event_list,
4590 .help = "displays a table of events defined for this target",
4593 .name = "curstate",
4594 .mode = COMMAND_EXEC,
4595 .jim_handler = jim_target_current_state,
4596 .help = "displays the current state of this target",
4599 .name = "arp_examine",
4600 .mode = COMMAND_EXEC,
4601 .jim_handler = jim_target_examine,
4602 .help = "used internally for reset processing",
4605 .name = "arp_halt_gdb",
4606 .mode = COMMAND_EXEC,
4607 .jim_handler = jim_target_halt_gdb,
4608 .help = "used internally for reset processing to halt GDB",
4611 .name = "arp_poll",
4612 .mode = COMMAND_EXEC,
4613 .jim_handler = jim_target_poll,
4614 .help = "used internally for reset processing",
4617 .name = "arp_reset",
4618 .mode = COMMAND_EXEC,
4619 .jim_handler = jim_target_reset,
4620 .help = "used internally for reset processing",
4623 .name = "arp_halt",
4624 .mode = COMMAND_EXEC,
4625 .jim_handler = jim_target_halt,
4626 .help = "used internally for reset processing",
4629 .name = "arp_waitstate",
4630 .mode = COMMAND_EXEC,
4631 .jim_handler = jim_target_wait_state,
4632 .help = "used internally for reset processing",
4635 .name = "invoke-event",
4636 .mode = COMMAND_EXEC,
4637 .jim_handler = jim_target_invoke_event,
4638 .help = "invoke handler for specified event",
4639 .usage = "event_name",
4641 COMMAND_REGISTRATION_DONE
4644 static int target_create(Jim_GetOptInfo *goi)
4646 Jim_Obj *new_cmd;
4647 Jim_Cmd *cmd;
4648 const char *cp;
4649 char *cp2;
4650 int e;
4651 int x;
4652 struct target *target;
4653 struct command_context *cmd_ctx;
4655 cmd_ctx = current_command_context(goi->interp);
4656 assert (cmd_ctx != NULL);
4658 if (goi->argc < 3) {
4659 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4660 return JIM_ERR;
4663 /* COMMAND */
4664 Jim_GetOpt_Obj(goi, &new_cmd);
4665 /* does this command exist? */
4666 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4667 if (cmd) {
4668 cp = Jim_GetString(new_cmd, NULL);
4669 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4670 return JIM_ERR;
4673 /* TYPE */
4674 e = Jim_GetOpt_String(goi, &cp2, NULL);
4675 cp = cp2;
4676 /* now does target type exist */
4677 for (x = 0 ; target_types[x] ; x++) {
4678 if (0 == strcmp(cp, target_types[x]->name)) {
4679 /* found */
4680 break;
4683 if (target_types[x] == NULL) {
4684 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4685 for (x = 0 ; target_types[x] ; x++) {
4686 if (target_types[x + 1]) {
4687 Jim_AppendStrings(goi->interp,
4688 Jim_GetResult(goi->interp),
4689 target_types[x]->name,
4690 ", ", NULL);
4691 } else {
4692 Jim_AppendStrings(goi->interp,
4693 Jim_GetResult(goi->interp),
4694 " or ",
4695 target_types[x]->name,NULL);
4698 return JIM_ERR;
4701 /* Create it */
4702 target = calloc(1,sizeof(struct target));
4703 /* set target number */
4704 target->target_number = new_target_number();
4706 /* allocate memory for each unique target type */
4707 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4709 memcpy(target->type, target_types[x], sizeof(struct target_type));
4711 /* will be set by "-endian" */
4712 target->endianness = TARGET_ENDIAN_UNKNOWN;
4714 /* default to first core, override with -coreid */
4715 target->coreid = 0;
4717 target->working_area = 0x0;
4718 target->working_area_size = 0x0;
4719 target->working_areas = NULL;
4720 target->backup_working_area = 0;
4722 target->state = TARGET_UNKNOWN;
4723 target->debug_reason = DBG_REASON_UNDEFINED;
4724 target->reg_cache = NULL;
4725 target->breakpoints = NULL;
4726 target->watchpoints = NULL;
4727 target->next = NULL;
4728 target->arch_info = NULL;
4730 target->display = 1;
4732 target->halt_issued = false;
4734 /* initialize trace information */
4735 target->trace_info = malloc(sizeof(struct trace));
4736 target->trace_info->num_trace_points = 0;
4737 target->trace_info->trace_points_size = 0;
4738 target->trace_info->trace_points = NULL;
4739 target->trace_info->trace_history_size = 0;
4740 target->trace_info->trace_history = NULL;
4741 target->trace_info->trace_history_pos = 0;
4742 target->trace_info->trace_history_overflowed = 0;
4744 target->dbgmsg = NULL;
4745 target->dbg_msg_enabled = 0;
4747 target->endianness = TARGET_ENDIAN_UNKNOWN;
4749 /* Do the rest as "configure" options */
4750 goi->isconfigure = 1;
4751 e = target_configure(goi, target);
4753 if (target->tap == NULL)
4755 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4756 e = JIM_ERR;
4759 if (e != JIM_OK) {
4760 free(target->type);
4761 free(target);
4762 return e;
4765 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4766 /* default endian to little if not specified */
4767 target->endianness = TARGET_LITTLE_ENDIAN;
4770 /* incase variant is not set */
4771 if (!target->variant)
4772 target->variant = strdup("");
4774 cp = Jim_GetString(new_cmd, NULL);
4775 target->cmd_name = strdup(cp);
4777 /* create the target specific commands */
4778 if (target->type->commands) {
4779 e = register_commands(cmd_ctx, NULL, target->type->commands);
4780 if (ERROR_OK != e)
4781 LOG_ERROR("unable to register '%s' commands", cp);
4783 if (target->type->target_create) {
4784 (*(target->type->target_create))(target, goi->interp);
4787 /* append to end of list */
4789 struct target **tpp;
4790 tpp = &(all_targets);
4791 while (*tpp) {
4792 tpp = &((*tpp)->next);
4794 *tpp = target;
4797 /* now - create the new target name command */
4798 const const struct command_registration target_subcommands[] = {
4800 .chain = target_instance_command_handlers,
4803 .chain = target->type->commands,
4805 COMMAND_REGISTRATION_DONE
4807 const const struct command_registration target_commands[] = {
4809 .name = cp,
4810 .mode = COMMAND_ANY,
4811 .help = "target command group",
4812 .chain = target_subcommands,
4814 COMMAND_REGISTRATION_DONE
4816 e = register_commands(cmd_ctx, NULL, target_commands);
4817 if (ERROR_OK != e)
4818 return JIM_ERR;
4820 struct command *c = command_find_in_context(cmd_ctx, cp);
4821 assert(c);
4822 command_set_handler_data(c, target);
4824 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4827 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4829 if (argc != 1)
4831 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4832 return JIM_ERR;
4834 struct command_context *cmd_ctx = current_command_context(interp);
4835 assert (cmd_ctx != NULL);
4837 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4838 return JIM_OK;
4841 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4843 if (argc != 1)
4845 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4846 return JIM_ERR;
4848 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4849 for (unsigned x = 0; NULL != target_types[x]; x++)
4851 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4852 Jim_NewStringObj(interp, target_types[x]->name, -1));
4854 return JIM_OK;
4857 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4859 if (argc != 1)
4861 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4862 return JIM_ERR;
4864 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4865 struct target *target = all_targets;
4866 while (target)
4868 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4869 Jim_NewStringObj(interp, target_name(target), -1));
4870 target = target->next;
4872 return JIM_OK;
4875 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4877 Jim_GetOptInfo goi;
4878 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4879 if (goi.argc < 3)
4881 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4882 "<name> <target_type> [<target_options> ...]");
4883 return JIM_ERR;
4885 return target_create(&goi);
4888 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4890 Jim_GetOptInfo goi;
4891 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4893 /* It's OK to remove this mechanism sometime after August 2010 or so */
4894 LOG_WARNING("don't use numbers as target identifiers; use names");
4895 if (goi.argc != 1)
4897 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
4898 return JIM_ERR;
4900 jim_wide w;
4901 int e = Jim_GetOpt_Wide(&goi, &w);
4902 if (e != JIM_OK)
4903 return JIM_ERR;
4905 struct target *target;
4906 for (target = all_targets; NULL != target; target = target->next)
4908 if (target->target_number != w)
4909 continue;
4911 Jim_SetResultString(goi.interp, target_name(target), -1);
4912 return JIM_OK;
4915 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
4916 Jim_SetResultFormatted(goi.interp,
4917 "Target: number %#s does not exist", wObj);
4918 Jim_FreeNewObj(interp, wObj);
4920 return JIM_ERR;
4923 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4925 if (argc != 1)
4927 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4928 return JIM_ERR;
4930 unsigned count = 0;
4931 struct target *target = all_targets;
4932 while (NULL != target)
4934 target = target->next;
4935 count++;
4937 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4938 return JIM_OK;
4941 static const struct command_registration target_subcommand_handlers[] = {
4943 .name = "init",
4944 .mode = COMMAND_CONFIG,
4945 .handler = handle_target_init_command,
4946 .help = "initialize targets",
4949 .name = "create",
4950 /* REVISIT this should be COMMAND_CONFIG ... */
4951 .mode = COMMAND_ANY,
4952 .jim_handler = jim_target_create,
4953 .usage = "name type '-chain-position' name [options ...]",
4954 .help = "Creates and selects a new target",
4957 .name = "current",
4958 .mode = COMMAND_ANY,
4959 .jim_handler = jim_target_current,
4960 .help = "Returns the currently selected target",
4963 .name = "types",
4964 .mode = COMMAND_ANY,
4965 .jim_handler = jim_target_types,
4966 .help = "Returns the available target types as "
4967 "a list of strings",
4970 .name = "names",
4971 .mode = COMMAND_ANY,
4972 .jim_handler = jim_target_names,
4973 .help = "Returns the names of all targets as a list of strings",
4976 .name = "number",
4977 .mode = COMMAND_ANY,
4978 .jim_handler = jim_target_number,
4979 .usage = "number",
4980 .help = "Returns the name of the numbered target "
4981 "(DEPRECATED)",
4984 .name = "count",
4985 .mode = COMMAND_ANY,
4986 .jim_handler = jim_target_count,
4987 .help = "Returns the number of targets as an integer "
4988 "(DEPRECATED)",
4990 COMMAND_REGISTRATION_DONE
4993 struct FastLoad
4995 uint32_t address;
4996 uint8_t *data;
4997 int length;
5001 static int fastload_num;
5002 static struct FastLoad *fastload;
5004 static void free_fastload(void)
5006 if (fastload != NULL)
5008 int i;
5009 for (i = 0; i < fastload_num; i++)
5011 if (fastload[i].data)
5012 free(fastload[i].data);
5014 free(fastload);
5015 fastload = NULL;
5022 COMMAND_HANDLER(handle_fast_load_image_command)
5024 uint8_t *buffer;
5025 size_t buf_cnt;
5026 uint32_t image_size;
5027 uint32_t min_address = 0;
5028 uint32_t max_address = 0xffffffff;
5029 int i;
5031 struct image image;
5033 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5034 &image, &min_address, &max_address);
5035 if (ERROR_OK != retval)
5036 return retval;
5038 struct duration bench;
5039 duration_start(&bench);
5041 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5042 if (retval != ERROR_OK)
5044 return retval;
5047 image_size = 0x0;
5048 retval = ERROR_OK;
5049 fastload_num = image.num_sections;
5050 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5051 if (fastload == NULL)
5053 command_print(CMD_CTX, "out of memory");
5054 image_close(&image);
5055 return ERROR_FAIL;
5057 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5058 for (i = 0; i < image.num_sections; i++)
5060 buffer = malloc(image.sections[i].size);
5061 if (buffer == NULL)
5063 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5064 (int)(image.sections[i].size));
5065 retval = ERROR_FAIL;
5066 break;
5069 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
5071 free(buffer);
5072 break;
5075 uint32_t offset = 0;
5076 uint32_t length = buf_cnt;
5079 /* DANGER!!! beware of unsigned comparision here!!! */
5081 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
5082 (image.sections[i].base_address < max_address))
5084 if (image.sections[i].base_address < min_address)
5086 /* clip addresses below */
5087 offset += min_address-image.sections[i].base_address;
5088 length -= offset;
5091 if (image.sections[i].base_address + buf_cnt > max_address)
5093 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5096 fastload[i].address = image.sections[i].base_address + offset;
5097 fastload[i].data = malloc(length);
5098 if (fastload[i].data == NULL)
5100 free(buffer);
5101 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5102 length);
5103 retval = ERROR_FAIL;
5104 break;
5106 memcpy(fastload[i].data, buffer + offset, length);
5107 fastload[i].length = length;
5109 image_size += length;
5110 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5111 (unsigned int)length,
5112 ((unsigned int)(image.sections[i].base_address + offset)));
5115 free(buffer);
5118 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5120 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5121 "in %fs (%0.3f KiB/s)", image_size,
5122 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5124 command_print(CMD_CTX,
5125 "WARNING: image has not been loaded to target!"
5126 "You can issue a 'fast_load' to finish loading.");
5129 image_close(&image);
5131 if (retval != ERROR_OK)
5133 free_fastload();
5136 return retval;
5139 COMMAND_HANDLER(handle_fast_load_command)
5141 if (CMD_ARGC > 0)
5142 return ERROR_COMMAND_SYNTAX_ERROR;
5143 if (fastload == NULL)
5145 LOG_ERROR("No image in memory");
5146 return ERROR_FAIL;
5148 int i;
5149 int ms = timeval_ms();
5150 int size = 0;
5151 int retval = ERROR_OK;
5152 for (i = 0; i < fastload_num;i++)
5154 struct target *target = get_current_target(CMD_CTX);
5155 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5156 (unsigned int)(fastload[i].address),
5157 (unsigned int)(fastload[i].length));
5158 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5159 if (retval != ERROR_OK)
5161 break;
5163 size += fastload[i].length;
5165 if (retval == ERROR_OK)
5167 int after = timeval_ms();
5168 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5170 return retval;
5173 static const struct command_registration target_command_handlers[] = {
5175 .name = "targets",
5176 .handler = handle_targets_command,
5177 .mode = COMMAND_ANY,
5178 .help = "change current default target (one parameter) "
5179 "or prints table of all targets (no parameters)",
5180 .usage = "[target]",
5183 .name = "target",
5184 .mode = COMMAND_CONFIG,
5185 .help = "configure target",
5187 .chain = target_subcommand_handlers,
5189 COMMAND_REGISTRATION_DONE
5192 int target_register_commands(struct command_context *cmd_ctx)
5194 return register_commands(cmd_ctx, NULL, target_command_handlers);
5197 static bool target_reset_nag = true;
5199 bool get_target_reset_nag(void)
5201 return target_reset_nag;
5204 COMMAND_HANDLER(handle_target_reset_nag)
5206 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5207 &target_reset_nag, "Nag after each reset about options to improve "
5208 "performance");
5211 static const struct command_registration target_exec_command_handlers[] = {
5213 .name = "fast_load_image",
5214 .handler = handle_fast_load_image_command,
5215 .mode = COMMAND_ANY,
5216 .help = "Load image into server memory for later use by "
5217 "fast_load; primarily for profiling",
5218 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5219 "[min_address [max_length]]",
5222 .name = "fast_load",
5223 .handler = handle_fast_load_command,
5224 .mode = COMMAND_EXEC,
5225 .help = "loads active fast load image to current target "
5226 "- mainly for profiling purposes",
5229 .name = "profile",
5230 .handler = handle_profile_command,
5231 .mode = COMMAND_EXEC,
5232 .help = "profiling samples the CPU PC",
5234 /** @todo don't register virt2phys() unless target supports it */
5236 .name = "virt2phys",
5237 .handler = handle_virt2phys_command,
5238 .mode = COMMAND_ANY,
5239 .help = "translate a virtual address into a physical address",
5240 .usage = "virtual_address",
5243 .name = "reg",
5244 .handler = handle_reg_command,
5245 .mode = COMMAND_EXEC,
5246 .help = "display or set a register; with no arguments, "
5247 "displays all registers and their values",
5248 .usage = "[(register_name|register_number) [value]]",
5251 .name = "poll",
5252 .handler = handle_poll_command,
5253 .mode = COMMAND_EXEC,
5254 .help = "poll target state; or reconfigure background polling",
5255 .usage = "['on'|'off']",
5258 .name = "wait_halt",
5259 .handler = handle_wait_halt_command,
5260 .mode = COMMAND_EXEC,
5261 .help = "wait up to the specified number of milliseconds "
5262 "(default 5) for a previously requested halt",
5263 .usage = "[milliseconds]",
5266 .name = "halt",
5267 .handler = handle_halt_command,
5268 .mode = COMMAND_EXEC,
5269 .help = "request target to halt, then wait up to the specified"
5270 "number of milliseconds (default 5) for it to complete",
5271 .usage = "[milliseconds]",
5274 .name = "resume",
5275 .handler = handle_resume_command,
5276 .mode = COMMAND_EXEC,
5277 .help = "resume target execution from current PC or address",
5278 .usage = "[address]",
5281 .name = "reset",
5282 .handler = handle_reset_command,
5283 .mode = COMMAND_EXEC,
5284 .usage = "[run|halt|init]",
5285 .help = "Reset all targets into the specified mode."
5286 "Default reset mode is run, if not given.",
5289 .name = "soft_reset_halt",
5290 .handler = handle_soft_reset_halt_command,
5291 .mode = COMMAND_EXEC,
5292 .help = "halt the target and do a soft reset",
5295 .name = "step",
5296 .handler = handle_step_command,
5297 .mode = COMMAND_EXEC,
5298 .help = "step one instruction from current PC or address",
5299 .usage = "[address]",
5302 .name = "mdw",
5303 .handler = handle_md_command,
5304 .mode = COMMAND_EXEC,
5305 .help = "display memory words",
5306 .usage = "['phys'] address [count]",
5309 .name = "mdh",
5310 .handler = handle_md_command,
5311 .mode = COMMAND_EXEC,
5312 .help = "display memory half-words",
5313 .usage = "['phys'] address [count]",
5316 .name = "mdb",
5317 .handler = handle_md_command,
5318 .mode = COMMAND_EXEC,
5319 .help = "display memory bytes",
5320 .usage = "['phys'] address [count]",
5323 .name = "mww",
5324 .handler = handle_mw_command,
5325 .mode = COMMAND_EXEC,
5326 .help = "write memory word",
5327 .usage = "['phys'] address value [count]",
5330 .name = "mwh",
5331 .handler = handle_mw_command,
5332 .mode = COMMAND_EXEC,
5333 .help = "write memory half-word",
5334 .usage = "['phys'] address value [count]",
5337 .name = "mwb",
5338 .handler = handle_mw_command,
5339 .mode = COMMAND_EXEC,
5340 .help = "write memory byte",
5341 .usage = "['phys'] address value [count]",
5344 .name = "bp",
5345 .handler = handle_bp_command,
5346 .mode = COMMAND_EXEC,
5347 .help = "list or set hardware or software breakpoint",
5348 .usage = "[address length ['hw']]",
5351 .name = "rbp",
5352 .handler = handle_rbp_command,
5353 .mode = COMMAND_EXEC,
5354 .help = "remove breakpoint",
5355 .usage = "address",
5358 .name = "wp",
5359 .handler = handle_wp_command,
5360 .mode = COMMAND_EXEC,
5361 .help = "list (no params) or create watchpoints",
5362 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5365 .name = "rwp",
5366 .handler = handle_rwp_command,
5367 .mode = COMMAND_EXEC,
5368 .help = "remove watchpoint",
5369 .usage = "address",
5372 .name = "load_image",
5373 .handler = handle_load_image_command,
5374 .mode = COMMAND_EXEC,
5375 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5376 "[min_address] [max_length]",
5379 .name = "dump_image",
5380 .handler = handle_dump_image_command,
5381 .mode = COMMAND_EXEC,
5382 .usage = "filename address size",
5385 .name = "verify_image",
5386 .handler = handle_verify_image_command,
5387 .mode = COMMAND_EXEC,
5388 .usage = "filename [offset [type]]",
5391 .name = "test_image",
5392 .handler = handle_test_image_command,
5393 .mode = COMMAND_EXEC,
5394 .usage = "filename [offset [type]]",
5397 .name = "mem2array",
5398 .mode = COMMAND_EXEC,
5399 .jim_handler = jim_mem2array,
5400 .help = "read 8/16/32 bit memory and return as a TCL array "
5401 "for script processing",
5402 .usage = "arrayname bitwidth address count",
5405 .name = "array2mem",
5406 .mode = COMMAND_EXEC,
5407 .jim_handler = jim_array2mem,
5408 .help = "convert a TCL array to memory locations "
5409 "and write the 8/16/32 bit values",
5410 .usage = "arrayname bitwidth address count",
5413 .name = "reset_nag",
5414 .handler = handle_target_reset_nag,
5415 .mode = COMMAND_ANY,
5416 .help = "Nag after each reset about options that could have been "
5417 "enabled to improve performance. ",
5418 .usage = "['enable'|'disable']",
5420 COMMAND_REGISTRATION_DONE
5422 static int target_register_user_commands(struct command_context *cmd_ctx)
5424 int retval = ERROR_OK;
5425 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5426 return retval;
5428 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5429 return retval;
5432 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);