tcl: remove silly ocd_ prefix to array2mem and mem2array
[openocd/genbsdl.git] / src / target / target.c
blob16caea5fc9a04c37a38106bf0c7b7905de185ea3
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_array2mem(Jim_Interp *interp, struct target *target,
50 int argc, Jim_Obj *const *argv);
51 static int target_mem2array(Jim_Interp *interp, struct target *target,
52 int argc, Jim_Obj *const *argv);
53 static int target_register_user_commands(struct command_context *cmd_ctx);
55 /* targets */
56 extern struct target_type arm7tdmi_target;
57 extern struct target_type arm720t_target;
58 extern struct target_type arm9tdmi_target;
59 extern struct target_type arm920t_target;
60 extern struct target_type arm966e_target;
61 extern struct target_type arm926ejs_target;
62 extern struct target_type fa526_target;
63 extern struct target_type feroceon_target;
64 extern struct target_type dragonite_target;
65 extern struct target_type xscale_target;
66 extern struct target_type cortexm3_target;
67 extern struct target_type cortexa8_target;
68 extern struct target_type arm11_target;
69 extern struct target_type mips_m4k_target;
70 extern struct target_type avr_target;
71 extern struct target_type dsp563xx_target;
72 extern struct target_type testee_target;
74 static struct target_type *target_types[] =
76 &arm7tdmi_target,
77 &arm9tdmi_target,
78 &arm920t_target,
79 &arm720t_target,
80 &arm966e_target,
81 &arm926ejs_target,
82 &fa526_target,
83 &feroceon_target,
84 &dragonite_target,
85 &xscale_target,
86 &cortexm3_target,
87 &cortexa8_target,
88 &arm11_target,
89 &mips_m4k_target,
90 &avr_target,
91 &dsp563xx_target,
92 &testee_target,
93 NULL,
96 struct target *all_targets = NULL;
97 static struct target_event_callback *target_event_callbacks = NULL;
98 static struct target_timer_callback *target_timer_callbacks = NULL;
99 static const int polling_interval = 100;
101 static const Jim_Nvp nvp_assert[] = {
102 { .name = "assert", NVP_ASSERT },
103 { .name = "deassert", NVP_DEASSERT },
104 { .name = "T", NVP_ASSERT },
105 { .name = "F", NVP_DEASSERT },
106 { .name = "t", NVP_ASSERT },
107 { .name = "f", NVP_DEASSERT },
108 { .name = NULL, .value = -1 }
111 static const Jim_Nvp nvp_error_target[] = {
112 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
113 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
114 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
115 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
116 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
117 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
118 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
119 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
120 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
121 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
122 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
123 { .value = -1, .name = NULL }
126 static const char *target_strerror_safe(int err)
128 const Jim_Nvp *n;
130 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
131 if (n->name == NULL) {
132 return "unknown";
133 } else {
134 return n->name;
138 static const Jim_Nvp nvp_target_event[] = {
139 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
140 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
142 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
143 { .value = TARGET_EVENT_HALTED, .name = "halted" },
144 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
145 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
146 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
148 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
149 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
151 /* historical name */
153 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
155 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
156 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
157 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
158 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
159 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
160 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
161 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
162 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
163 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
164 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
165 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
167 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
168 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
170 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
171 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
173 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
174 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
176 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
177 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
179 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
180 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
182 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
183 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
184 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
186 { .name = NULL, .value = -1 }
189 static const Jim_Nvp nvp_target_state[] = {
190 { .name = "unknown", .value = TARGET_UNKNOWN },
191 { .name = "running", .value = TARGET_RUNNING },
192 { .name = "halted", .value = TARGET_HALTED },
193 { .name = "reset", .value = TARGET_RESET },
194 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
195 { .name = NULL, .value = -1 },
198 static const Jim_Nvp nvp_target_debug_reason [] = {
199 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
200 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
201 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
202 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
203 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
204 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
205 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
206 { .name = NULL, .value = -1 },
209 static const Jim_Nvp nvp_target_endian[] = {
210 { .name = "big", .value = TARGET_BIG_ENDIAN },
211 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
212 { .name = "be", .value = TARGET_BIG_ENDIAN },
213 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
214 { .name = NULL, .value = -1 },
217 static const Jim_Nvp nvp_reset_modes[] = {
218 { .name = "unknown", .value = RESET_UNKNOWN },
219 { .name = "run" , .value = RESET_RUN },
220 { .name = "halt" , .value = RESET_HALT },
221 { .name = "init" , .value = RESET_INIT },
222 { .name = NULL , .value = -1 },
225 const char *debug_reason_name(struct target *t)
227 const char *cp;
229 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
230 t->debug_reason)->name;
231 if (!cp) {
232 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
233 cp = "(*BUG*unknown*BUG*)";
235 return cp;
238 const char *
239 target_state_name( struct target *t )
241 const char *cp;
242 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
243 if( !cp ){
244 LOG_ERROR("Invalid target state: %d", (int)(t->state));
245 cp = "(*BUG*unknown*BUG*)";
247 return cp;
250 /* determine the number of the new target */
251 static int new_target_number(void)
253 struct target *t;
254 int x;
256 /* number is 0 based */
257 x = -1;
258 t = all_targets;
259 while (t) {
260 if (x < t->target_number) {
261 x = t->target_number;
263 t = t->next;
265 return x + 1;
268 /* read a uint32_t from a buffer in target memory endianness */
269 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
271 if (target->endianness == TARGET_LITTLE_ENDIAN)
272 return le_to_h_u32(buffer);
273 else
274 return be_to_h_u32(buffer);
277 /* read a uint16_t from a buffer in target memory endianness */
278 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
280 if (target->endianness == TARGET_LITTLE_ENDIAN)
281 return le_to_h_u16(buffer);
282 else
283 return be_to_h_u16(buffer);
286 /* read a uint8_t from a buffer in target memory endianness */
287 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
289 return *buffer & 0x0ff;
292 /* write a uint32_t to a buffer in target memory endianness */
293 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
295 if (target->endianness == TARGET_LITTLE_ENDIAN)
296 h_u32_to_le(buffer, value);
297 else
298 h_u32_to_be(buffer, value);
301 /* write a uint16_t to a buffer in target memory endianness */
302 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
304 if (target->endianness == TARGET_LITTLE_ENDIAN)
305 h_u16_to_le(buffer, value);
306 else
307 h_u16_to_be(buffer, value);
310 /* write a uint8_t to a buffer in target memory endianness */
311 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
313 *buffer = value;
316 /* return a pointer to a configured target; id is name or number */
317 struct target *get_target(const char *id)
319 struct target *target;
321 /* try as tcltarget name */
322 for (target = all_targets; target; target = target->next) {
323 if (target->cmd_name == NULL)
324 continue;
325 if (strcmp(id, target->cmd_name) == 0)
326 return target;
329 /* It's OK to remove this fallback sometime after August 2010 or so */
331 /* no match, try as number */
332 unsigned num;
333 if (parse_uint(id, &num) != ERROR_OK)
334 return NULL;
336 for (target = all_targets; target; target = target->next) {
337 if (target->target_number == (int)num) {
338 LOG_WARNING("use '%s' as target identifier, not '%u'",
339 target->cmd_name, num);
340 return target;
344 return NULL;
347 /* returns a pointer to the n-th configured target */
348 static struct target *get_target_by_num(int num)
350 struct target *target = all_targets;
352 while (target) {
353 if (target->target_number == num) {
354 return target;
356 target = target->next;
359 return NULL;
362 struct target* get_current_target(struct command_context *cmd_ctx)
364 struct target *target = get_target_by_num(cmd_ctx->current_target);
366 if (target == NULL)
368 LOG_ERROR("BUG: current_target out of bounds");
369 exit(-1);
372 return target;
375 int target_poll(struct target *target)
377 int retval;
379 /* We can't poll until after examine */
380 if (!target_was_examined(target))
382 /* Fail silently lest we pollute the log */
383 return ERROR_FAIL;
386 retval = target->type->poll(target);
387 if (retval != ERROR_OK)
388 return retval;
390 if (target->halt_issued)
392 if (target->state == TARGET_HALTED)
394 target->halt_issued = false;
395 } else
397 long long t = timeval_ms() - target->halt_issued_time;
398 if (t>1000)
400 target->halt_issued = false;
401 LOG_INFO("Halt timed out, wake up GDB.");
402 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
407 return ERROR_OK;
410 int target_halt(struct target *target)
412 int retval;
413 /* We can't poll until after examine */
414 if (!target_was_examined(target))
416 LOG_ERROR("Target not examined yet");
417 return ERROR_FAIL;
420 retval = target->type->halt(target);
421 if (retval != ERROR_OK)
422 return retval;
424 target->halt_issued = true;
425 target->halt_issued_time = timeval_ms();
427 return ERROR_OK;
431 * Make the target (re)start executing using its saved execution
432 * context (possibly with some modifications).
434 * @param target Which target should start executing.
435 * @param current True to use the target's saved program counter instead
436 * of the address parameter
437 * @param address Optionally used as the program counter.
438 * @param handle_breakpoints True iff breakpoints at the resumption PC
439 * should be skipped. (For example, maybe execution was stopped by
440 * such a breakpoint, in which case it would be counterprodutive to
441 * let it re-trigger.
442 * @param debug_execution False if all working areas allocated by OpenOCD
443 * should be released and/or restored to their original contents.
444 * (This would for example be true to run some downloaded "helper"
445 * algorithm code, which resides in one such working buffer and uses
446 * another for data storage.)
448 * @todo Resolve the ambiguity about what the "debug_execution" flag
449 * signifies. For example, Target implementations don't agree on how
450 * it relates to invalidation of the register cache, or to whether
451 * breakpoints and watchpoints should be enabled. (It would seem wrong
452 * to enable breakpoints when running downloaded "helper" algorithms
453 * (debug_execution true), since the breakpoints would be set to match
454 * target firmware being debugged, not the helper algorithm.... and
455 * enabling them could cause such helpers to malfunction (for example,
456 * by overwriting data with a breakpoint instruction. On the other
457 * hand the infrastructure for running such helpers might use this
458 * procedure but rely on hardware breakpoint to detect termination.)
460 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
462 int retval;
464 /* We can't poll until after examine */
465 if (!target_was_examined(target))
467 LOG_ERROR("Target not examined yet");
468 return ERROR_FAIL;
471 /* note that resume *must* be asynchronous. The CPU can halt before
472 * we poll. The CPU can even halt at the current PC as a result of
473 * a software breakpoint being inserted by (a bug?) the application.
475 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
476 return retval;
478 return retval;
481 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
483 char buf[100];
484 int retval;
485 Jim_Nvp *n;
486 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
487 if (n->name == NULL) {
488 LOG_ERROR("invalid reset mode");
489 return ERROR_FAIL;
492 /* disable polling during reset to make reset event scripts
493 * more predictable, i.e. dr/irscan & pathmove in events will
494 * not have JTAG operations injected into the middle of a sequence.
496 bool save_poll = jtag_poll_get_enabled();
498 jtag_poll_set_enabled(false);
500 sprintf(buf, "ocd_process_reset %s", n->name);
501 retval = Jim_Eval(cmd_ctx->interp, buf);
503 jtag_poll_set_enabled(save_poll);
505 if (retval != JIM_OK) {
506 Jim_PrintErrorMessage(cmd_ctx->interp);
507 return ERROR_FAIL;
510 /* We want any events to be processed before the prompt */
511 retval = target_call_timer_callbacks_now();
513 struct target *target;
514 for (target = all_targets; target; target = target->next) {
515 target->type->check_reset(target);
518 return retval;
521 static int identity_virt2phys(struct target *target,
522 uint32_t virtual, uint32_t *physical)
524 *physical = virtual;
525 return ERROR_OK;
528 static int no_mmu(struct target *target, int *enabled)
530 *enabled = 0;
531 return ERROR_OK;
534 static int default_examine(struct target *target)
536 target_set_examined(target);
537 return ERROR_OK;
540 /* no check by default */
541 static int default_check_reset(struct target *target)
543 return ERROR_OK;
546 int target_examine_one(struct target *target)
548 return target->type->examine(target);
551 static int jtag_enable_callback(enum jtag_event event, void *priv)
553 struct target *target = priv;
555 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
556 return ERROR_OK;
558 jtag_unregister_event_callback(jtag_enable_callback, target);
559 return target_examine_one(target);
563 /* Targets that correctly implement init + examine, i.e.
564 * no communication with target during init:
566 * XScale
568 int target_examine(void)
570 int retval = ERROR_OK;
571 struct target *target;
573 for (target = all_targets; target; target = target->next)
575 /* defer examination, but don't skip it */
576 if (!target->tap->enabled) {
577 jtag_register_event_callback(jtag_enable_callback,
578 target);
579 continue;
581 if ((retval = target_examine_one(target)) != ERROR_OK)
582 return retval;
584 return retval;
586 const char *target_type_name(struct target *target)
588 return target->type->name;
591 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
593 if (!target_was_examined(target))
595 LOG_ERROR("Target not examined yet");
596 return ERROR_FAIL;
598 return target->type->write_memory_imp(target, address, size, count, buffer);
601 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
603 if (!target_was_examined(target))
605 LOG_ERROR("Target not examined yet");
606 return ERROR_FAIL;
608 return target->type->read_memory_imp(target, address, size, count, buffer);
611 static int target_soft_reset_halt_imp(struct target *target)
613 if (!target_was_examined(target))
615 LOG_ERROR("Target not examined yet");
616 return ERROR_FAIL;
618 if (!target->type->soft_reset_halt_imp) {
619 LOG_ERROR("Target %s does not support soft_reset_halt",
620 target_name(target));
621 return ERROR_FAIL;
623 return target->type->soft_reset_halt_imp(target);
627 * Downloads a target-specific native code algorithm to the target,
628 * and executes it. * Note that some targets may need to set up, enable,
629 * and tear down a breakpoint (hard or * soft) to detect algorithm
630 * termination, while others may support lower overhead schemes where
631 * soft breakpoints embedded in the algorithm automatically terminate the
632 * algorithm.
634 * @param target used to run the algorithm
635 * @param arch_info target-specific description of the algorithm.
637 int target_run_algorithm(struct target *target,
638 int num_mem_params, struct mem_param *mem_params,
639 int num_reg_params, struct reg_param *reg_param,
640 uint32_t entry_point, uint32_t exit_point,
641 int timeout_ms, void *arch_info)
643 int retval = ERROR_FAIL;
645 if (!target_was_examined(target))
647 LOG_ERROR("Target not examined yet");
648 goto done;
650 if (!target->type->run_algorithm) {
651 LOG_ERROR("Target type '%s' does not support %s",
652 target_type_name(target), __func__);
653 goto done;
656 target->running_alg = true;
657 retval = target->type->run_algorithm(target,
658 num_mem_params, mem_params,
659 num_reg_params, reg_param,
660 entry_point, exit_point, timeout_ms, arch_info);
661 target->running_alg = false;
663 done:
664 return retval;
668 int target_read_memory(struct target *target,
669 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
671 return target->type->read_memory(target, address, size, count, buffer);
674 static int target_read_phys_memory(struct target *target,
675 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
677 return target->type->read_phys_memory(target, address, size, count, buffer);
680 int target_write_memory(struct target *target,
681 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
683 return target->type->write_memory(target, address, size, count, buffer);
686 static int target_write_phys_memory(struct target *target,
687 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
689 return target->type->write_phys_memory(target, address, size, count, buffer);
692 int target_bulk_write_memory(struct target *target,
693 uint32_t address, uint32_t count, uint8_t *buffer)
695 return target->type->bulk_write_memory(target, address, count, buffer);
698 int target_add_breakpoint(struct target *target,
699 struct breakpoint *breakpoint)
701 if (target->state != TARGET_HALTED) {
702 LOG_WARNING("target %s is not halted", target->cmd_name);
703 return ERROR_TARGET_NOT_HALTED;
705 return target->type->add_breakpoint(target, breakpoint);
707 int target_remove_breakpoint(struct target *target,
708 struct breakpoint *breakpoint)
710 return target->type->remove_breakpoint(target, breakpoint);
713 int target_add_watchpoint(struct target *target,
714 struct watchpoint *watchpoint)
716 if (target->state != TARGET_HALTED) {
717 LOG_WARNING("target %s is not halted", target->cmd_name);
718 return ERROR_TARGET_NOT_HALTED;
720 return target->type->add_watchpoint(target, watchpoint);
722 int target_remove_watchpoint(struct target *target,
723 struct watchpoint *watchpoint)
725 return target->type->remove_watchpoint(target, watchpoint);
728 int target_get_gdb_reg_list(struct target *target,
729 struct reg **reg_list[], int *reg_list_size)
731 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
733 int target_step(struct target *target,
734 int current, uint32_t address, int handle_breakpoints)
736 return target->type->step(target, current, address, handle_breakpoints);
741 * Reset the @c examined flag for the given target.
742 * Pure paranoia -- targets are zeroed on allocation.
744 static void target_reset_examined(struct target *target)
746 target->examined = false;
749 static int
750 err_read_phys_memory(struct target *target, uint32_t address,
751 uint32_t size, uint32_t count, uint8_t *buffer)
753 LOG_ERROR("Not implemented: %s", __func__);
754 return ERROR_FAIL;
757 static int
758 err_write_phys_memory(struct target *target, uint32_t address,
759 uint32_t size, uint32_t count, uint8_t *buffer)
761 LOG_ERROR("Not implemented: %s", __func__);
762 return ERROR_FAIL;
765 static int handle_target(void *priv);
767 static int target_init_one(struct command_context *cmd_ctx,
768 struct target *target)
770 target_reset_examined(target);
772 struct target_type *type = target->type;
773 if (type->examine == NULL)
774 type->examine = default_examine;
776 if (type->check_reset== NULL)
777 type->check_reset = default_check_reset;
779 int retval = type->init_target(cmd_ctx, target);
780 if (ERROR_OK != retval)
782 LOG_ERROR("target '%s' init failed", target_name(target));
783 return retval;
787 * @todo get rid of those *memory_imp() methods, now that all
788 * callers are using target_*_memory() accessors ... and make
789 * sure the "physical" paths handle the same issues.
791 /* a non-invasive way(in terms of patches) to add some code that
792 * runs before the type->write/read_memory implementation
794 type->write_memory_imp = target->type->write_memory;
795 type->write_memory = target_write_memory_imp;
797 type->read_memory_imp = target->type->read_memory;
798 type->read_memory = target_read_memory_imp;
800 type->soft_reset_halt_imp = target->type->soft_reset_halt;
801 type->soft_reset_halt = target_soft_reset_halt_imp;
803 /* Sanity-check MMU support ... stub in what we must, to help
804 * implement it in stages, but warn if we need to do so.
806 if (type->mmu)
808 if (type->write_phys_memory == NULL)
810 LOG_ERROR("type '%s' is missing write_phys_memory",
811 type->name);
812 type->write_phys_memory = err_write_phys_memory;
814 if (type->read_phys_memory == NULL)
816 LOG_ERROR("type '%s' is missing read_phys_memory",
817 type->name);
818 type->read_phys_memory = err_read_phys_memory;
820 if (type->virt2phys == NULL)
822 LOG_ERROR("type '%s' is missing virt2phys", type->name);
823 type->virt2phys = identity_virt2phys;
826 else
828 /* Make sure no-MMU targets all behave the same: make no
829 * distinction between physical and virtual addresses, and
830 * ensure that virt2phys() is always an identity mapping.
832 if (type->write_phys_memory || type->read_phys_memory
833 || type->virt2phys)
835 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
838 type->mmu = no_mmu;
839 type->write_phys_memory = type->write_memory;
840 type->read_phys_memory = type->read_memory;
841 type->virt2phys = identity_virt2phys;
843 return ERROR_OK;
846 static int target_init(struct command_context *cmd_ctx)
848 struct target *target;
849 int retval;
851 for (target = all_targets; target; target = target->next)
853 retval = target_init_one(cmd_ctx, target);
854 if (ERROR_OK != retval)
855 return retval;
858 if (!all_targets)
859 return ERROR_OK;
861 retval = target_register_user_commands(cmd_ctx);
862 if (ERROR_OK != retval)
863 return retval;
865 retval = target_register_timer_callback(&handle_target,
866 polling_interval, 1, cmd_ctx->interp);
867 if (ERROR_OK != retval)
868 return retval;
870 return ERROR_OK;
873 COMMAND_HANDLER(handle_target_init_command)
875 if (CMD_ARGC != 0)
876 return ERROR_COMMAND_SYNTAX_ERROR;
878 static bool target_initialized = false;
879 if (target_initialized)
881 LOG_INFO("'target init' has already been called");
882 return ERROR_OK;
884 target_initialized = true;
886 LOG_DEBUG("Initializing targets...");
887 return target_init(CMD_CTX);
890 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
892 struct target_event_callback **callbacks_p = &target_event_callbacks;
894 if (callback == NULL)
896 return ERROR_INVALID_ARGUMENTS;
899 if (*callbacks_p)
901 while ((*callbacks_p)->next)
902 callbacks_p = &((*callbacks_p)->next);
903 callbacks_p = &((*callbacks_p)->next);
906 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
907 (*callbacks_p)->callback = callback;
908 (*callbacks_p)->priv = priv;
909 (*callbacks_p)->next = NULL;
911 return ERROR_OK;
914 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
916 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
917 struct timeval now;
919 if (callback == NULL)
921 return ERROR_INVALID_ARGUMENTS;
924 if (*callbacks_p)
926 while ((*callbacks_p)->next)
927 callbacks_p = &((*callbacks_p)->next);
928 callbacks_p = &((*callbacks_p)->next);
931 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
932 (*callbacks_p)->callback = callback;
933 (*callbacks_p)->periodic = periodic;
934 (*callbacks_p)->time_ms = time_ms;
936 gettimeofday(&now, NULL);
937 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
938 time_ms -= (time_ms % 1000);
939 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
940 if ((*callbacks_p)->when.tv_usec > 1000000)
942 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
943 (*callbacks_p)->when.tv_sec += 1;
946 (*callbacks_p)->priv = priv;
947 (*callbacks_p)->next = NULL;
949 return ERROR_OK;
952 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
954 struct target_event_callback **p = &target_event_callbacks;
955 struct target_event_callback *c = target_event_callbacks;
957 if (callback == NULL)
959 return ERROR_INVALID_ARGUMENTS;
962 while (c)
964 struct target_event_callback *next = c->next;
965 if ((c->callback == callback) && (c->priv == priv))
967 *p = next;
968 free(c);
969 return ERROR_OK;
971 else
972 p = &(c->next);
973 c = next;
976 return ERROR_OK;
979 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
981 struct target_timer_callback **p = &target_timer_callbacks;
982 struct target_timer_callback *c = target_timer_callbacks;
984 if (callback == NULL)
986 return ERROR_INVALID_ARGUMENTS;
989 while (c)
991 struct target_timer_callback *next = c->next;
992 if ((c->callback == callback) && (c->priv == priv))
994 *p = next;
995 free(c);
996 return ERROR_OK;
998 else
999 p = &(c->next);
1000 c = next;
1003 return ERROR_OK;
1006 int target_call_event_callbacks(struct target *target, enum target_event event)
1008 struct target_event_callback *callback = target_event_callbacks;
1009 struct target_event_callback *next_callback;
1011 if (event == TARGET_EVENT_HALTED)
1013 /* execute early halted first */
1014 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1017 LOG_DEBUG("target event %i (%s)",
1018 event,
1019 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1021 target_handle_event(target, event);
1023 while (callback)
1025 next_callback = callback->next;
1026 callback->callback(target, event, callback->priv);
1027 callback = next_callback;
1030 return ERROR_OK;
1033 static int target_timer_callback_periodic_restart(
1034 struct target_timer_callback *cb, struct timeval *now)
1036 int time_ms = cb->time_ms;
1037 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1038 time_ms -= (time_ms % 1000);
1039 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1040 if (cb->when.tv_usec > 1000000)
1042 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1043 cb->when.tv_sec += 1;
1045 return ERROR_OK;
1048 static int target_call_timer_callback(struct target_timer_callback *cb,
1049 struct timeval *now)
1051 cb->callback(cb->priv);
1053 if (cb->periodic)
1054 return target_timer_callback_periodic_restart(cb, now);
1056 return target_unregister_timer_callback(cb->callback, cb->priv);
1059 static int target_call_timer_callbacks_check_time(int checktime)
1061 keep_alive();
1063 struct timeval now;
1064 gettimeofday(&now, NULL);
1066 struct target_timer_callback *callback = target_timer_callbacks;
1067 while (callback)
1069 // cleaning up may unregister and free this callback
1070 struct target_timer_callback *next_callback = callback->next;
1072 bool call_it = callback->callback &&
1073 ((!checktime && callback->periodic) ||
1074 now.tv_sec > callback->when.tv_sec ||
1075 (now.tv_sec == callback->when.tv_sec &&
1076 now.tv_usec >= callback->when.tv_usec));
1078 if (call_it)
1080 int retval = target_call_timer_callback(callback, &now);
1081 if (retval != ERROR_OK)
1082 return retval;
1085 callback = next_callback;
1088 return ERROR_OK;
1091 int target_call_timer_callbacks(void)
1093 return target_call_timer_callbacks_check_time(1);
1096 /* invoke periodic callbacks immediately */
1097 int target_call_timer_callbacks_now(void)
1099 return target_call_timer_callbacks_check_time(0);
1102 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1104 struct working_area *c = target->working_areas;
1105 struct working_area *new_wa = NULL;
1107 /* Reevaluate working area address based on MMU state*/
1108 if (target->working_areas == NULL)
1110 int retval;
1111 int enabled;
1113 retval = target->type->mmu(target, &enabled);
1114 if (retval != ERROR_OK)
1116 return retval;
1119 if (!enabled) {
1120 if (target->working_area_phys_spec) {
1121 LOG_DEBUG("MMU disabled, using physical "
1122 "address for working memory 0x%08x",
1123 (unsigned)target->working_area_phys);
1124 target->working_area = target->working_area_phys;
1125 } else {
1126 LOG_ERROR("No working memory available. "
1127 "Specify -work-area-phys to target.");
1128 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1130 } else {
1131 if (target->working_area_virt_spec) {
1132 LOG_DEBUG("MMU enabled, using virtual "
1133 "address for working memory 0x%08x",
1134 (unsigned)target->working_area_virt);
1135 target->working_area = target->working_area_virt;
1136 } else {
1137 LOG_ERROR("No working memory available. "
1138 "Specify -work-area-virt to target.");
1139 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1144 /* only allocate multiples of 4 byte */
1145 if (size % 4)
1147 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1148 size = (size + 3) & (~3);
1151 /* see if there's already a matching working area */
1152 while (c)
1154 if ((c->free) && (c->size == size))
1156 new_wa = c;
1157 break;
1159 c = c->next;
1162 /* if not, allocate a new one */
1163 if (!new_wa)
1165 struct working_area **p = &target->working_areas;
1166 uint32_t first_free = target->working_area;
1167 uint32_t free_size = target->working_area_size;
1169 c = target->working_areas;
1170 while (c)
1172 first_free += c->size;
1173 free_size -= c->size;
1174 p = &c->next;
1175 c = c->next;
1178 if (free_size < size)
1180 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1183 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1185 new_wa = malloc(sizeof(struct working_area));
1186 new_wa->next = NULL;
1187 new_wa->size = size;
1188 new_wa->address = first_free;
1190 if (target->backup_working_area)
1192 int retval;
1193 new_wa->backup = malloc(new_wa->size);
1194 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1196 free(new_wa->backup);
1197 free(new_wa);
1198 return retval;
1201 else
1203 new_wa->backup = NULL;
1206 /* put new entry in list */
1207 *p = new_wa;
1210 /* mark as used, and return the new (reused) area */
1211 new_wa->free = 0;
1212 *area = new_wa;
1214 /* user pointer */
1215 new_wa->user = area;
1217 return ERROR_OK;
1220 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1222 int retval;
1224 retval = target_alloc_working_area_try(target, size, area);
1225 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1227 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1229 return retval;
1233 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1235 if (area->free)
1236 return ERROR_OK;
1238 if (restore && target->backup_working_area)
1240 int retval;
1241 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1242 return retval;
1245 area->free = 1;
1247 /* mark user pointer invalid */
1248 *area->user = NULL;
1249 area->user = NULL;
1251 return ERROR_OK;
1254 int target_free_working_area(struct target *target, struct working_area *area)
1256 return target_free_working_area_restore(target, area, 1);
1259 /* free resources and restore memory, if restoring memory fails,
1260 * free up resources anyway
1262 static void target_free_all_working_areas_restore(struct target *target, int restore)
1264 struct working_area *c = target->working_areas;
1266 while (c)
1268 struct working_area *next = c->next;
1269 target_free_working_area_restore(target, c, restore);
1271 if (c->backup)
1272 free(c->backup);
1274 free(c);
1276 c = next;
1279 target->working_areas = NULL;
1282 void target_free_all_working_areas(struct target *target)
1284 target_free_all_working_areas_restore(target, 1);
1287 int target_arch_state(struct target *target)
1289 int retval;
1290 if (target == NULL)
1292 LOG_USER("No target has been configured");
1293 return ERROR_OK;
1296 LOG_USER("target state: %s", target_state_name( target ));
1298 if (target->state != TARGET_HALTED)
1299 return ERROR_OK;
1301 retval = target->type->arch_state(target);
1302 return retval;
1305 /* Single aligned words are guaranteed to use 16 or 32 bit access
1306 * mode respectively, otherwise data is handled as quickly as
1307 * possible
1309 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1311 int retval;
1312 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1313 (int)size, (unsigned)address);
1315 if (!target_was_examined(target))
1317 LOG_ERROR("Target not examined yet");
1318 return ERROR_FAIL;
1321 if (size == 0) {
1322 return ERROR_OK;
1325 if ((address + size - 1) < address)
1327 /* GDB can request this when e.g. PC is 0xfffffffc*/
1328 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1329 (unsigned)address,
1330 (unsigned)size);
1331 return ERROR_FAIL;
1334 if (((address % 2) == 0) && (size == 2))
1336 return target_write_memory(target, address, 2, 1, buffer);
1339 /* handle unaligned head bytes */
1340 if (address % 4)
1342 uint32_t unaligned = 4 - (address % 4);
1344 if (unaligned > size)
1345 unaligned = size;
1347 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1348 return retval;
1350 buffer += unaligned;
1351 address += unaligned;
1352 size -= unaligned;
1355 /* handle aligned words */
1356 if (size >= 4)
1358 int aligned = size - (size % 4);
1360 /* use bulk writes above a certain limit. This may have to be changed */
1361 if (aligned > 128)
1363 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1364 return retval;
1366 else
1368 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1369 return retval;
1372 buffer += aligned;
1373 address += aligned;
1374 size -= aligned;
1377 /* handle tail writes of less than 4 bytes */
1378 if (size > 0)
1380 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1381 return retval;
1384 return ERROR_OK;
1387 /* Single aligned words are guaranteed to use 16 or 32 bit access
1388 * mode respectively, otherwise data is handled as quickly as
1389 * possible
1391 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1393 int retval;
1394 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1395 (int)size, (unsigned)address);
1397 if (!target_was_examined(target))
1399 LOG_ERROR("Target not examined yet");
1400 return ERROR_FAIL;
1403 if (size == 0) {
1404 return ERROR_OK;
1407 if ((address + size - 1) < address)
1409 /* GDB can request this when e.g. PC is 0xfffffffc*/
1410 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1411 address,
1412 size);
1413 return ERROR_FAIL;
1416 if (((address % 2) == 0) && (size == 2))
1418 return target_read_memory(target, address, 2, 1, buffer);
1421 /* handle unaligned head bytes */
1422 if (address % 4)
1424 uint32_t unaligned = 4 - (address % 4);
1426 if (unaligned > size)
1427 unaligned = size;
1429 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1430 return retval;
1432 buffer += unaligned;
1433 address += unaligned;
1434 size -= unaligned;
1437 /* handle aligned words */
1438 if (size >= 4)
1440 int aligned = size - (size % 4);
1442 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1443 return retval;
1445 buffer += aligned;
1446 address += aligned;
1447 size -= aligned;
1450 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1451 if(size >=2)
1453 int aligned = size - (size%2);
1454 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1455 if (retval != ERROR_OK)
1456 return retval;
1458 buffer += aligned;
1459 address += aligned;
1460 size -= aligned;
1462 /* handle tail writes of less than 4 bytes */
1463 if (size > 0)
1465 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1466 return retval;
1469 return ERROR_OK;
1472 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1474 uint8_t *buffer;
1475 int retval;
1476 uint32_t i;
1477 uint32_t checksum = 0;
1478 if (!target_was_examined(target))
1480 LOG_ERROR("Target not examined yet");
1481 return ERROR_FAIL;
1484 if ((retval = target->type->checksum_memory(target, address,
1485 size, &checksum)) != ERROR_OK)
1487 buffer = malloc(size);
1488 if (buffer == NULL)
1490 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1491 return ERROR_INVALID_ARGUMENTS;
1493 retval = target_read_buffer(target, address, size, buffer);
1494 if (retval != ERROR_OK)
1496 free(buffer);
1497 return retval;
1500 /* convert to target endianess */
1501 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1503 uint32_t target_data;
1504 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1505 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1508 retval = image_calculate_checksum(buffer, size, &checksum);
1509 free(buffer);
1512 *crc = checksum;
1514 return retval;
1517 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1519 int retval;
1520 if (!target_was_examined(target))
1522 LOG_ERROR("Target not examined yet");
1523 return ERROR_FAIL;
1526 if (target->type->blank_check_memory == 0)
1527 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1529 retval = target->type->blank_check_memory(target, address, size, blank);
1531 return retval;
1534 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1536 uint8_t value_buf[4];
1537 if (!target_was_examined(target))
1539 LOG_ERROR("Target not examined yet");
1540 return ERROR_FAIL;
1543 int retval = target_read_memory(target, address, 4, 1, value_buf);
1545 if (retval == ERROR_OK)
1547 *value = target_buffer_get_u32(target, value_buf);
1548 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1549 address,
1550 *value);
1552 else
1554 *value = 0x0;
1555 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1556 address);
1559 return retval;
1562 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1564 uint8_t value_buf[2];
1565 if (!target_was_examined(target))
1567 LOG_ERROR("Target not examined yet");
1568 return ERROR_FAIL;
1571 int retval = target_read_memory(target, address, 2, 1, value_buf);
1573 if (retval == ERROR_OK)
1575 *value = target_buffer_get_u16(target, value_buf);
1576 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1577 address,
1578 *value);
1580 else
1582 *value = 0x0;
1583 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1584 address);
1587 return retval;
1590 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1592 int retval = target_read_memory(target, address, 1, 1, value);
1593 if (!target_was_examined(target))
1595 LOG_ERROR("Target not examined yet");
1596 return ERROR_FAIL;
1599 if (retval == ERROR_OK)
1601 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1602 address,
1603 *value);
1605 else
1607 *value = 0x0;
1608 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1609 address);
1612 return retval;
1615 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1617 int retval;
1618 uint8_t value_buf[4];
1619 if (!target_was_examined(target))
1621 LOG_ERROR("Target not examined yet");
1622 return ERROR_FAIL;
1625 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1626 address,
1627 value);
1629 target_buffer_set_u32(target, value_buf, value);
1630 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1632 LOG_DEBUG("failed: %i", retval);
1635 return retval;
1638 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1640 int retval;
1641 uint8_t value_buf[2];
1642 if (!target_was_examined(target))
1644 LOG_ERROR("Target not examined yet");
1645 return ERROR_FAIL;
1648 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1649 address,
1650 value);
1652 target_buffer_set_u16(target, value_buf, value);
1653 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1655 LOG_DEBUG("failed: %i", retval);
1658 return retval;
1661 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1663 int retval;
1664 if (!target_was_examined(target))
1666 LOG_ERROR("Target not examined yet");
1667 return ERROR_FAIL;
1670 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1671 address, value);
1673 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1675 LOG_DEBUG("failed: %i", retval);
1678 return retval;
1681 COMMAND_HANDLER(handle_targets_command)
1683 struct target *target = all_targets;
1685 if (CMD_ARGC == 1)
1687 target = get_target(CMD_ARGV[0]);
1688 if (target == NULL) {
1689 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1690 goto DumpTargets;
1692 if (!target->tap->enabled) {
1693 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1694 "can't be the current target\n",
1695 target->tap->dotted_name);
1696 return ERROR_FAIL;
1699 CMD_CTX->current_target = target->target_number;
1700 return ERROR_OK;
1702 DumpTargets:
1704 target = all_targets;
1705 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1706 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1707 while (target)
1709 const char *state;
1710 char marker = ' ';
1712 if (target->tap->enabled)
1713 state = target_state_name( target );
1714 else
1715 state = "tap-disabled";
1717 if (CMD_CTX->current_target == target->target_number)
1718 marker = '*';
1720 /* keep columns lined up to match the headers above */
1721 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1722 target->target_number,
1723 marker,
1724 target_name(target),
1725 target_type_name(target),
1726 Jim_Nvp_value2name_simple(nvp_target_endian,
1727 target->endianness)->name,
1728 target->tap->dotted_name,
1729 state);
1730 target = target->next;
1733 return ERROR_OK;
1736 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1738 static int powerDropout;
1739 static int srstAsserted;
1741 static int runPowerRestore;
1742 static int runPowerDropout;
1743 static int runSrstAsserted;
1744 static int runSrstDeasserted;
1746 static int sense_handler(void)
1748 static int prevSrstAsserted = 0;
1749 static int prevPowerdropout = 0;
1751 int retval;
1752 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1753 return retval;
1755 int powerRestored;
1756 powerRestored = prevPowerdropout && !powerDropout;
1757 if (powerRestored)
1759 runPowerRestore = 1;
1762 long long current = timeval_ms();
1763 static long long lastPower = 0;
1764 int waitMore = lastPower + 2000 > current;
1765 if (powerDropout && !waitMore)
1767 runPowerDropout = 1;
1768 lastPower = current;
1771 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1772 return retval;
1774 int srstDeasserted;
1775 srstDeasserted = prevSrstAsserted && !srstAsserted;
1777 static long long lastSrst = 0;
1778 waitMore = lastSrst + 2000 > current;
1779 if (srstDeasserted && !waitMore)
1781 runSrstDeasserted = 1;
1782 lastSrst = current;
1785 if (!prevSrstAsserted && srstAsserted)
1787 runSrstAsserted = 1;
1790 prevSrstAsserted = srstAsserted;
1791 prevPowerdropout = powerDropout;
1793 if (srstDeasserted || powerRestored)
1795 /* Other than logging the event we can't do anything here.
1796 * Issuing a reset is a particularly bad idea as we might
1797 * be inside a reset already.
1801 return ERROR_OK;
1804 static int backoff_times = 0;
1805 static int backoff_count = 0;
1807 /* process target state changes */
1808 static int handle_target(void *priv)
1810 Jim_Interp *interp = (Jim_Interp *)priv;
1811 int retval = ERROR_OK;
1813 if (!is_jtag_poll_safe())
1815 /* polling is disabled currently */
1816 return ERROR_OK;
1819 /* we do not want to recurse here... */
1820 static int recursive = 0;
1821 if (! recursive)
1823 recursive = 1;
1824 sense_handler();
1825 /* danger! running these procedures can trigger srst assertions and power dropouts.
1826 * We need to avoid an infinite loop/recursion here and we do that by
1827 * clearing the flags after running these events.
1829 int did_something = 0;
1830 if (runSrstAsserted)
1832 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1833 Jim_Eval(interp, "srst_asserted");
1834 did_something = 1;
1836 if (runSrstDeasserted)
1838 Jim_Eval(interp, "srst_deasserted");
1839 did_something = 1;
1841 if (runPowerDropout)
1843 LOG_INFO("Power dropout detected, running power_dropout proc.");
1844 Jim_Eval(interp, "power_dropout");
1845 did_something = 1;
1847 if (runPowerRestore)
1849 Jim_Eval(interp, "power_restore");
1850 did_something = 1;
1853 if (did_something)
1855 /* clear detect flags */
1856 sense_handler();
1859 /* clear action flags */
1861 runSrstAsserted = 0;
1862 runSrstDeasserted = 0;
1863 runPowerRestore = 0;
1864 runPowerDropout = 0;
1866 recursive = 0;
1869 if (backoff_times > backoff_count)
1871 /* do not poll this time as we failed previously */
1872 backoff_count++;
1873 return ERROR_OK;
1875 backoff_count = 0;
1877 /* Poll targets for state changes unless that's globally disabled.
1878 * Skip targets that are currently disabled.
1880 for (struct target *target = all_targets;
1881 is_jtag_poll_safe() && target;
1882 target = target->next)
1884 if (!target->tap->enabled)
1885 continue;
1887 /* only poll target if we've got power and srst isn't asserted */
1888 if (!powerDropout && !srstAsserted)
1890 /* polling may fail silently until the target has been examined */
1891 if ((retval = target_poll(target)) != ERROR_OK)
1893 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1894 if (backoff_times * polling_interval < 5000)
1896 backoff_times *= 2;
1897 backoff_times++;
1899 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1901 /* Tell GDB to halt the debugger. This allows the user to
1902 * run monitor commands to handle the situation.
1904 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1905 return retval;
1907 /* Since we succeeded, we reset backoff count */
1908 if (backoff_times > 0)
1910 LOG_USER("Polling succeeded again");
1912 backoff_times = 0;
1916 return retval;
1919 COMMAND_HANDLER(handle_reg_command)
1921 struct target *target;
1922 struct reg *reg = NULL;
1923 unsigned count = 0;
1924 char *value;
1926 LOG_DEBUG("-");
1928 target = get_current_target(CMD_CTX);
1930 /* list all available registers for the current target */
1931 if (CMD_ARGC == 0)
1933 struct reg_cache *cache = target->reg_cache;
1935 count = 0;
1936 while (cache)
1938 unsigned i;
1940 command_print(CMD_CTX, "===== %s", cache->name);
1942 for (i = 0, reg = cache->reg_list;
1943 i < cache->num_regs;
1944 i++, reg++, count++)
1946 /* only print cached values if they are valid */
1947 if (reg->valid) {
1948 value = buf_to_str(reg->value,
1949 reg->size, 16);
1950 command_print(CMD_CTX,
1951 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1952 count, reg->name,
1953 reg->size, value,
1954 reg->dirty
1955 ? " (dirty)"
1956 : "");
1957 free(value);
1958 } else {
1959 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1960 count, reg->name,
1961 reg->size) ;
1964 cache = cache->next;
1967 return ERROR_OK;
1970 /* access a single register by its ordinal number */
1971 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1973 unsigned num;
1974 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1976 struct reg_cache *cache = target->reg_cache;
1977 count = 0;
1978 while (cache)
1980 unsigned i;
1981 for (i = 0; i < cache->num_regs; i++)
1983 if (count++ == num)
1985 reg = &cache->reg_list[i];
1986 break;
1989 if (reg)
1990 break;
1991 cache = cache->next;
1994 if (!reg)
1996 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1997 return ERROR_OK;
1999 } else /* access a single register by its name */
2001 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2003 if (!reg)
2005 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2006 return ERROR_OK;
2010 /* display a register */
2011 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2013 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2014 reg->valid = 0;
2016 if (reg->valid == 0)
2018 reg->type->get(reg);
2020 value = buf_to_str(reg->value, reg->size, 16);
2021 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2022 free(value);
2023 return ERROR_OK;
2026 /* set register value */
2027 if (CMD_ARGC == 2)
2029 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2030 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2032 reg->type->set(reg, buf);
2034 value = buf_to_str(reg->value, reg->size, 16);
2035 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2036 free(value);
2038 free(buf);
2040 return ERROR_OK;
2043 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2045 return ERROR_OK;
2048 COMMAND_HANDLER(handle_poll_command)
2050 int retval = ERROR_OK;
2051 struct target *target = get_current_target(CMD_CTX);
2053 if (CMD_ARGC == 0)
2055 command_print(CMD_CTX, "background polling: %s",
2056 jtag_poll_get_enabled() ? "on" : "off");
2057 command_print(CMD_CTX, "TAP: %s (%s)",
2058 target->tap->dotted_name,
2059 target->tap->enabled ? "enabled" : "disabled");
2060 if (!target->tap->enabled)
2061 return ERROR_OK;
2062 if ((retval = target_poll(target)) != ERROR_OK)
2063 return retval;
2064 if ((retval = target_arch_state(target)) != ERROR_OK)
2065 return retval;
2067 else if (CMD_ARGC == 1)
2069 bool enable;
2070 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2071 jtag_poll_set_enabled(enable);
2073 else
2075 return ERROR_COMMAND_SYNTAX_ERROR;
2078 return retval;
2081 COMMAND_HANDLER(handle_wait_halt_command)
2083 if (CMD_ARGC > 1)
2084 return ERROR_COMMAND_SYNTAX_ERROR;
2086 unsigned ms = 5000;
2087 if (1 == CMD_ARGC)
2089 int retval = parse_uint(CMD_ARGV[0], &ms);
2090 if (ERROR_OK != retval)
2092 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2093 return ERROR_COMMAND_SYNTAX_ERROR;
2095 // convert seconds (given) to milliseconds (needed)
2096 ms *= 1000;
2099 struct target *target = get_current_target(CMD_CTX);
2100 return target_wait_state(target, TARGET_HALTED, ms);
2103 /* wait for target state to change. The trick here is to have a low
2104 * latency for short waits and not to suck up all the CPU time
2105 * on longer waits.
2107 * After 500ms, keep_alive() is invoked
2109 int target_wait_state(struct target *target, enum target_state state, int ms)
2111 int retval;
2112 long long then = 0, cur;
2113 int once = 1;
2115 for (;;)
2117 if ((retval = target_poll(target)) != ERROR_OK)
2118 return retval;
2119 if (target->state == state)
2121 break;
2123 cur = timeval_ms();
2124 if (once)
2126 once = 0;
2127 then = timeval_ms();
2128 LOG_DEBUG("waiting for target %s...",
2129 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2132 if (cur-then > 500)
2134 keep_alive();
2137 if ((cur-then) > ms)
2139 LOG_ERROR("timed out while waiting for target %s",
2140 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2141 return ERROR_FAIL;
2145 return ERROR_OK;
2148 COMMAND_HANDLER(handle_halt_command)
2150 LOG_DEBUG("-");
2152 struct target *target = get_current_target(CMD_CTX);
2153 int retval = target_halt(target);
2154 if (ERROR_OK != retval)
2155 return retval;
2157 if (CMD_ARGC == 1)
2159 unsigned wait_local;
2160 retval = parse_uint(CMD_ARGV[0], &wait_local);
2161 if (ERROR_OK != retval)
2162 return ERROR_COMMAND_SYNTAX_ERROR;
2163 if (!wait_local)
2164 return ERROR_OK;
2167 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2170 COMMAND_HANDLER(handle_soft_reset_halt_command)
2172 struct target *target = get_current_target(CMD_CTX);
2174 LOG_USER("requesting target halt and executing a soft reset");
2176 target->type->soft_reset_halt(target);
2178 return ERROR_OK;
2181 COMMAND_HANDLER(handle_reset_command)
2183 if (CMD_ARGC > 1)
2184 return ERROR_COMMAND_SYNTAX_ERROR;
2186 enum target_reset_mode reset_mode = RESET_RUN;
2187 if (CMD_ARGC == 1)
2189 const Jim_Nvp *n;
2190 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2191 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2192 return ERROR_COMMAND_SYNTAX_ERROR;
2194 reset_mode = n->value;
2197 /* reset *all* targets */
2198 return target_process_reset(CMD_CTX, reset_mode);
2202 COMMAND_HANDLER(handle_resume_command)
2204 int current = 1;
2205 if (CMD_ARGC > 1)
2206 return ERROR_COMMAND_SYNTAX_ERROR;
2208 struct target *target = get_current_target(CMD_CTX);
2209 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2211 /* with no CMD_ARGV, resume from current pc, addr = 0,
2212 * with one arguments, addr = CMD_ARGV[0],
2213 * handle breakpoints, not debugging */
2214 uint32_t addr = 0;
2215 if (CMD_ARGC == 1)
2217 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2218 current = 0;
2221 return target_resume(target, current, addr, 1, 0);
2224 COMMAND_HANDLER(handle_step_command)
2226 if (CMD_ARGC > 1)
2227 return ERROR_COMMAND_SYNTAX_ERROR;
2229 LOG_DEBUG("-");
2231 /* with no CMD_ARGV, step from current pc, addr = 0,
2232 * with one argument addr = CMD_ARGV[0],
2233 * handle breakpoints, debugging */
2234 uint32_t addr = 0;
2235 int current_pc = 1;
2236 if (CMD_ARGC == 1)
2238 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2239 current_pc = 0;
2242 struct target *target = get_current_target(CMD_CTX);
2244 return target->type->step(target, current_pc, addr, 1);
2247 static void handle_md_output(struct command_context *cmd_ctx,
2248 struct target *target, uint32_t address, unsigned size,
2249 unsigned count, const uint8_t *buffer)
2251 const unsigned line_bytecnt = 32;
2252 unsigned line_modulo = line_bytecnt / size;
2254 char output[line_bytecnt * 4 + 1];
2255 unsigned output_len = 0;
2257 const char *value_fmt;
2258 switch (size) {
2259 case 4: value_fmt = "%8.8x "; break;
2260 case 2: value_fmt = "%4.4x "; break;
2261 case 1: value_fmt = "%2.2x "; break;
2262 default:
2263 /* "can't happen", caller checked */
2264 LOG_ERROR("invalid memory read size: %u", size);
2265 return;
2268 for (unsigned i = 0; i < count; i++)
2270 if (i % line_modulo == 0)
2272 output_len += snprintf(output + output_len,
2273 sizeof(output) - output_len,
2274 "0x%8.8x: ",
2275 (unsigned)(address + (i*size)));
2278 uint32_t value = 0;
2279 const uint8_t *value_ptr = buffer + i * size;
2280 switch (size) {
2281 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2282 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2283 case 1: value = *value_ptr;
2285 output_len += snprintf(output + output_len,
2286 sizeof(output) - output_len,
2287 value_fmt, value);
2289 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2291 command_print(cmd_ctx, "%s", output);
2292 output_len = 0;
2297 COMMAND_HANDLER(handle_md_command)
2299 if (CMD_ARGC < 1)
2300 return ERROR_COMMAND_SYNTAX_ERROR;
2302 unsigned size = 0;
2303 switch (CMD_NAME[2]) {
2304 case 'w': size = 4; break;
2305 case 'h': size = 2; break;
2306 case 'b': size = 1; break;
2307 default: return ERROR_COMMAND_SYNTAX_ERROR;
2310 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2311 int (*fn)(struct target *target,
2312 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2313 if (physical)
2315 CMD_ARGC--;
2316 CMD_ARGV++;
2317 fn=target_read_phys_memory;
2318 } else
2320 fn=target_read_memory;
2322 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2324 return ERROR_COMMAND_SYNTAX_ERROR;
2327 uint32_t address;
2328 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2330 unsigned count = 1;
2331 if (CMD_ARGC == 2)
2332 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2334 uint8_t *buffer = calloc(count, size);
2336 struct target *target = get_current_target(CMD_CTX);
2337 int retval = fn(target, address, size, count, buffer);
2338 if (ERROR_OK == retval)
2339 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2341 free(buffer);
2343 return retval;
2346 typedef int (*target_write_fn)(struct target *target,
2347 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2349 static int target_write_memory_fast(struct target *target,
2350 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2352 return target_write_buffer(target, address, size * count, buffer);
2355 static int target_fill_mem(struct target *target,
2356 uint32_t address,
2357 target_write_fn fn,
2358 unsigned data_size,
2359 /* value */
2360 uint32_t b,
2361 /* count */
2362 unsigned c)
2364 /* We have to write in reasonably large chunks to be able
2365 * to fill large memory areas with any sane speed */
2366 const unsigned chunk_size = 16384;
2367 uint8_t *target_buf = malloc(chunk_size * data_size);
2368 if (target_buf == NULL)
2370 LOG_ERROR("Out of memory");
2371 return ERROR_FAIL;
2374 for (unsigned i = 0; i < chunk_size; i ++)
2376 switch (data_size)
2378 case 4:
2379 target_buffer_set_u32(target, target_buf + i*data_size, b);
2380 break;
2381 case 2:
2382 target_buffer_set_u16(target, target_buf + i*data_size, b);
2383 break;
2384 case 1:
2385 target_buffer_set_u8(target, target_buf + i*data_size, b);
2386 break;
2387 default:
2388 exit(-1);
2392 int retval = ERROR_OK;
2394 for (unsigned x = 0; x < c; x += chunk_size)
2396 unsigned current;
2397 current = c - x;
2398 if (current > chunk_size)
2400 current = chunk_size;
2402 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2403 if (retval != ERROR_OK)
2405 break;
2407 /* avoid GDB timeouts */
2408 keep_alive();
2410 free(target_buf);
2412 return retval;
2416 COMMAND_HANDLER(handle_mw_command)
2418 if (CMD_ARGC < 2)
2420 return ERROR_COMMAND_SYNTAX_ERROR;
2422 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2423 target_write_fn fn;
2424 if (physical)
2426 CMD_ARGC--;
2427 CMD_ARGV++;
2428 fn=target_write_phys_memory;
2429 } else
2431 fn = target_write_memory_fast;
2433 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2434 return ERROR_COMMAND_SYNTAX_ERROR;
2436 uint32_t address;
2437 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2439 uint32_t value;
2440 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2442 unsigned count = 1;
2443 if (CMD_ARGC == 3)
2444 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2446 struct target *target = get_current_target(CMD_CTX);
2447 unsigned wordsize;
2448 switch (CMD_NAME[2])
2450 case 'w':
2451 wordsize = 4;
2452 break;
2453 case 'h':
2454 wordsize = 2;
2455 break;
2456 case 'b':
2457 wordsize = 1;
2458 break;
2459 default:
2460 return ERROR_COMMAND_SYNTAX_ERROR;
2463 return target_fill_mem(target, address, fn, wordsize, value, count);
2466 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2467 uint32_t *min_address, uint32_t *max_address)
2469 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2470 return ERROR_COMMAND_SYNTAX_ERROR;
2472 /* a base address isn't always necessary,
2473 * default to 0x0 (i.e. don't relocate) */
2474 if (CMD_ARGC >= 2)
2476 uint32_t addr;
2477 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2478 image->base_address = addr;
2479 image->base_address_set = 1;
2481 else
2482 image->base_address_set = 0;
2484 image->start_address_set = 0;
2486 if (CMD_ARGC >= 4)
2488 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2490 if (CMD_ARGC == 5)
2492 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2493 // use size (given) to find max (required)
2494 *max_address += *min_address;
2497 if (*min_address > *max_address)
2498 return ERROR_COMMAND_SYNTAX_ERROR;
2500 return ERROR_OK;
2503 COMMAND_HANDLER(handle_load_image_command)
2505 uint8_t *buffer;
2506 size_t buf_cnt;
2507 uint32_t image_size;
2508 uint32_t min_address = 0;
2509 uint32_t max_address = 0xffffffff;
2510 int i;
2511 struct image image;
2513 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2514 &image, &min_address, &max_address);
2515 if (ERROR_OK != retval)
2516 return retval;
2518 struct target *target = get_current_target(CMD_CTX);
2520 struct duration bench;
2521 duration_start(&bench);
2523 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2525 return ERROR_OK;
2528 image_size = 0x0;
2529 retval = ERROR_OK;
2530 for (i = 0; i < image.num_sections; i++)
2532 buffer = malloc(image.sections[i].size);
2533 if (buffer == NULL)
2535 command_print(CMD_CTX,
2536 "error allocating buffer for section (%d bytes)",
2537 (int)(image.sections[i].size));
2538 break;
2541 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2543 free(buffer);
2544 break;
2547 uint32_t offset = 0;
2548 uint32_t length = buf_cnt;
2550 /* DANGER!!! beware of unsigned comparision here!!! */
2552 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2553 (image.sections[i].base_address < max_address))
2555 if (image.sections[i].base_address < min_address)
2557 /* clip addresses below */
2558 offset += min_address-image.sections[i].base_address;
2559 length -= offset;
2562 if (image.sections[i].base_address + buf_cnt > max_address)
2564 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2567 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2569 free(buffer);
2570 break;
2572 image_size += length;
2573 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2574 (unsigned int)length,
2575 image.sections[i].base_address + offset);
2578 free(buffer);
2581 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2583 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2584 "in %fs (%0.3f KiB/s)", image_size,
2585 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2588 image_close(&image);
2590 return retval;
2594 COMMAND_HANDLER(handle_dump_image_command)
2596 struct fileio fileio;
2598 uint8_t buffer[560];
2599 int retvaltemp;
2602 struct target *target = get_current_target(CMD_CTX);
2604 if (CMD_ARGC != 3)
2606 command_print(CMD_CTX, "usage: dump_image <filename> <address> <size>");
2607 return ERROR_OK;
2610 uint32_t address;
2611 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2612 uint32_t size;
2613 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2615 if (fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2617 return ERROR_OK;
2620 struct duration bench;
2621 duration_start(&bench);
2623 int retval = ERROR_OK;
2624 while (size > 0)
2626 size_t size_written;
2627 uint32_t this_run_size = (size > 560) ? 560 : size;
2628 retval = target_read_buffer(target, address, this_run_size, buffer);
2629 if (retval != ERROR_OK)
2631 break;
2634 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2635 if (retval != ERROR_OK)
2637 break;
2640 size -= this_run_size;
2641 address += this_run_size;
2644 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2645 return retvaltemp;
2647 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2649 command_print(CMD_CTX,
2650 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)fileio.size,
2651 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2654 return retval;
2657 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2659 uint8_t *buffer;
2660 size_t buf_cnt;
2661 uint32_t image_size;
2662 int i;
2663 int retval;
2664 uint32_t checksum = 0;
2665 uint32_t mem_checksum = 0;
2667 struct image image;
2669 struct target *target = get_current_target(CMD_CTX);
2671 if (CMD_ARGC < 1)
2673 return ERROR_COMMAND_SYNTAX_ERROR;
2676 if (!target)
2678 LOG_ERROR("no target selected");
2679 return ERROR_FAIL;
2682 struct duration bench;
2683 duration_start(&bench);
2685 if (CMD_ARGC >= 2)
2687 uint32_t addr;
2688 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2689 image.base_address = addr;
2690 image.base_address_set = 1;
2692 else
2694 image.base_address_set = 0;
2695 image.base_address = 0x0;
2698 image.start_address_set = 0;
2700 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2702 return retval;
2705 image_size = 0x0;
2706 int diffs = 0;
2707 retval = ERROR_OK;
2708 for (i = 0; i < image.num_sections; i++)
2710 buffer = malloc(image.sections[i].size);
2711 if (buffer == NULL)
2713 command_print(CMD_CTX,
2714 "error allocating buffer for section (%d bytes)",
2715 (int)(image.sections[i].size));
2716 break;
2718 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2720 free(buffer);
2721 break;
2724 if (verify)
2726 /* calculate checksum of image */
2727 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2728 if (retval != ERROR_OK)
2730 free(buffer);
2731 break;
2734 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2735 if (retval != ERROR_OK)
2737 free(buffer);
2738 break;
2741 if (checksum != mem_checksum)
2743 /* failed crc checksum, fall back to a binary compare */
2744 uint8_t *data;
2746 if (diffs == 0)
2748 LOG_ERROR("checksum mismatch - attempting binary compare");
2751 data = (uint8_t*)malloc(buf_cnt);
2753 /* Can we use 32bit word accesses? */
2754 int size = 1;
2755 int count = buf_cnt;
2756 if ((count % 4) == 0)
2758 size *= 4;
2759 count /= 4;
2761 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2762 if (retval == ERROR_OK)
2764 uint32_t t;
2765 for (t = 0; t < buf_cnt; t++)
2767 if (data[t] != buffer[t])
2769 command_print(CMD_CTX,
2770 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2771 diffs,
2772 (unsigned)(t + image.sections[i].base_address),
2773 data[t],
2774 buffer[t]);
2775 if (diffs++ >= 127)
2777 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2778 free(data);
2779 free(buffer);
2780 goto done;
2783 keep_alive();
2786 free(data);
2788 } else
2790 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2791 image.sections[i].base_address,
2792 buf_cnt);
2795 free(buffer);
2796 image_size += buf_cnt;
2798 if (diffs > 0)
2800 command_print(CMD_CTX, "No more differences found.");
2802 done:
2803 if (diffs > 0)
2805 retval = ERROR_FAIL;
2807 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2809 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2810 "in %fs (%0.3f KiB/s)", image_size,
2811 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2814 image_close(&image);
2816 return retval;
2819 COMMAND_HANDLER(handle_verify_image_command)
2821 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2824 COMMAND_HANDLER(handle_test_image_command)
2826 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2829 static int handle_bp_command_list(struct command_context *cmd_ctx)
2831 struct target *target = get_current_target(cmd_ctx);
2832 struct breakpoint *breakpoint = target->breakpoints;
2833 while (breakpoint)
2835 if (breakpoint->type == BKPT_SOFT)
2837 char* buf = buf_to_str(breakpoint->orig_instr,
2838 breakpoint->length, 16);
2839 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2840 breakpoint->address,
2841 breakpoint->length,
2842 breakpoint->set, buf);
2843 free(buf);
2845 else
2847 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2848 breakpoint->address,
2849 breakpoint->length, breakpoint->set);
2852 breakpoint = breakpoint->next;
2854 return ERROR_OK;
2857 static int handle_bp_command_set(struct command_context *cmd_ctx,
2858 uint32_t addr, uint32_t length, int hw)
2860 struct target *target = get_current_target(cmd_ctx);
2861 int retval = breakpoint_add(target, addr, length, hw);
2862 if (ERROR_OK == retval)
2863 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2864 else
2865 LOG_ERROR("Failure setting breakpoint");
2866 return retval;
2869 COMMAND_HANDLER(handle_bp_command)
2871 if (CMD_ARGC == 0)
2872 return handle_bp_command_list(CMD_CTX);
2874 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2876 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2877 return ERROR_COMMAND_SYNTAX_ERROR;
2880 uint32_t addr;
2881 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2882 uint32_t length;
2883 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2885 int hw = BKPT_SOFT;
2886 if (CMD_ARGC == 3)
2888 if (strcmp(CMD_ARGV[2], "hw") == 0)
2889 hw = BKPT_HARD;
2890 else
2891 return ERROR_COMMAND_SYNTAX_ERROR;
2894 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2897 COMMAND_HANDLER(handle_rbp_command)
2899 if (CMD_ARGC != 1)
2900 return ERROR_COMMAND_SYNTAX_ERROR;
2902 uint32_t addr;
2903 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2905 struct target *target = get_current_target(CMD_CTX);
2906 breakpoint_remove(target, addr);
2908 return ERROR_OK;
2911 COMMAND_HANDLER(handle_wp_command)
2913 struct target *target = get_current_target(CMD_CTX);
2915 if (CMD_ARGC == 0)
2917 struct watchpoint *watchpoint = target->watchpoints;
2919 while (watchpoint)
2921 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2922 ", len: 0x%8.8" PRIx32
2923 ", r/w/a: %i, value: 0x%8.8" PRIx32
2924 ", mask: 0x%8.8" PRIx32,
2925 watchpoint->address,
2926 watchpoint->length,
2927 (int)watchpoint->rw,
2928 watchpoint->value,
2929 watchpoint->mask);
2930 watchpoint = watchpoint->next;
2932 return ERROR_OK;
2935 enum watchpoint_rw type = WPT_ACCESS;
2936 uint32_t addr = 0;
2937 uint32_t length = 0;
2938 uint32_t data_value = 0x0;
2939 uint32_t data_mask = 0xffffffff;
2941 switch (CMD_ARGC)
2943 case 5:
2944 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2945 // fall through
2946 case 4:
2947 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2948 // fall through
2949 case 3:
2950 switch (CMD_ARGV[2][0])
2952 case 'r':
2953 type = WPT_READ;
2954 break;
2955 case 'w':
2956 type = WPT_WRITE;
2957 break;
2958 case 'a':
2959 type = WPT_ACCESS;
2960 break;
2961 default:
2962 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2963 return ERROR_COMMAND_SYNTAX_ERROR;
2965 // fall through
2966 case 2:
2967 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2968 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2969 break;
2971 default:
2972 command_print(CMD_CTX, "usage: wp [address length "
2973 "[(r|w|a) [value [mask]]]]");
2974 return ERROR_COMMAND_SYNTAX_ERROR;
2977 int retval = watchpoint_add(target, addr, length, type,
2978 data_value, data_mask);
2979 if (ERROR_OK != retval)
2980 LOG_ERROR("Failure setting watchpoints");
2982 return retval;
2985 COMMAND_HANDLER(handle_rwp_command)
2987 if (CMD_ARGC != 1)
2988 return ERROR_COMMAND_SYNTAX_ERROR;
2990 uint32_t addr;
2991 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2993 struct target *target = get_current_target(CMD_CTX);
2994 watchpoint_remove(target, addr);
2996 return ERROR_OK;
3001 * Translate a virtual address to a physical address.
3003 * The low-level target implementation must have logged a detailed error
3004 * which is forwarded to telnet/GDB session.
3006 COMMAND_HANDLER(handle_virt2phys_command)
3008 if (CMD_ARGC != 1)
3009 return ERROR_COMMAND_SYNTAX_ERROR;
3011 uint32_t va;
3012 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3013 uint32_t pa;
3015 struct target *target = get_current_target(CMD_CTX);
3016 int retval = target->type->virt2phys(target, va, &pa);
3017 if (retval == ERROR_OK)
3018 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3020 return retval;
3023 static void writeData(FILE *f, const void *data, size_t len)
3025 size_t written = fwrite(data, 1, len, f);
3026 if (written != len)
3027 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3030 static void writeLong(FILE *f, int l)
3032 int i;
3033 for (i = 0; i < 4; i++)
3035 char c = (l >> (i*8))&0xff;
3036 writeData(f, &c, 1);
3041 static void writeString(FILE *f, char *s)
3043 writeData(f, s, strlen(s));
3046 /* Dump a gmon.out histogram file. */
3047 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3049 uint32_t i;
3050 FILE *f = fopen(filename, "w");
3051 if (f == NULL)
3052 return;
3053 writeString(f, "gmon");
3054 writeLong(f, 0x00000001); /* Version */
3055 writeLong(f, 0); /* padding */
3056 writeLong(f, 0); /* padding */
3057 writeLong(f, 0); /* padding */
3059 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3060 writeData(f, &zero, 1);
3062 /* figure out bucket size */
3063 uint32_t min = samples[0];
3064 uint32_t max = samples[0];
3065 for (i = 0; i < sampleNum; i++)
3067 if (min > samples[i])
3069 min = samples[i];
3071 if (max < samples[i])
3073 max = samples[i];
3077 int addressSpace = (max-min + 1);
3079 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
3080 uint32_t length = addressSpace;
3081 if (length > maxBuckets)
3083 length = maxBuckets;
3085 int *buckets = malloc(sizeof(int)*length);
3086 if (buckets == NULL)
3088 fclose(f);
3089 return;
3091 memset(buckets, 0, sizeof(int)*length);
3092 for (i = 0; i < sampleNum;i++)
3094 uint32_t address = samples[i];
3095 long long a = address-min;
3096 long long b = length-1;
3097 long long c = addressSpace-1;
3098 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3099 buckets[index_t]++;
3102 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3103 writeLong(f, min); /* low_pc */
3104 writeLong(f, max); /* high_pc */
3105 writeLong(f, length); /* # of samples */
3106 writeLong(f, 64000000); /* 64MHz */
3107 writeString(f, "seconds");
3108 for (i = 0; i < (15-strlen("seconds")); i++)
3109 writeData(f, &zero, 1);
3110 writeString(f, "s");
3112 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3114 char *data = malloc(2*length);
3115 if (data != NULL)
3117 for (i = 0; i < length;i++)
3119 int val;
3120 val = buckets[i];
3121 if (val > 65535)
3123 val = 65535;
3125 data[i*2]=val&0xff;
3126 data[i*2 + 1]=(val >> 8)&0xff;
3128 free(buckets);
3129 writeData(f, data, length * 2);
3130 free(data);
3131 } else
3133 free(buckets);
3136 fclose(f);
3139 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3140 * which will be used as a random sampling of PC */
3141 COMMAND_HANDLER(handle_profile_command)
3143 struct target *target = get_current_target(CMD_CTX);
3144 struct timeval timeout, now;
3146 gettimeofday(&timeout, NULL);
3147 if (CMD_ARGC != 2)
3149 return ERROR_COMMAND_SYNTAX_ERROR;
3151 unsigned offset;
3152 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3154 timeval_add_time(&timeout, offset, 0);
3157 * @todo: Some cores let us sample the PC without the
3158 * annoying halt/resume step; for example, ARMv7 PCSR.
3159 * Provide a way to use that more efficient mechanism.
3162 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3164 static const int maxSample = 10000;
3165 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3166 if (samples == NULL)
3167 return ERROR_OK;
3169 int numSamples = 0;
3170 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3171 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3173 for (;;)
3175 int retval;
3176 target_poll(target);
3177 if (target->state == TARGET_HALTED)
3179 uint32_t t=*((uint32_t *)reg->value);
3180 samples[numSamples++]=t;
3181 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3182 target_poll(target);
3183 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3184 } else if (target->state == TARGET_RUNNING)
3186 /* We want to quickly sample the PC. */
3187 if ((retval = target_halt(target)) != ERROR_OK)
3189 free(samples);
3190 return retval;
3192 } else
3194 command_print(CMD_CTX, "Target not halted or running");
3195 retval = ERROR_OK;
3196 break;
3198 if (retval != ERROR_OK)
3200 break;
3203 gettimeofday(&now, NULL);
3204 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3206 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3207 if ((retval = target_poll(target)) != ERROR_OK)
3209 free(samples);
3210 return retval;
3212 if (target->state == TARGET_HALTED)
3214 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3216 if ((retval = target_poll(target)) != ERROR_OK)
3218 free(samples);
3219 return retval;
3221 writeGmon(samples, numSamples, CMD_ARGV[1]);
3222 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3223 break;
3226 free(samples);
3228 return ERROR_OK;
3231 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3233 char *namebuf;
3234 Jim_Obj *nameObjPtr, *valObjPtr;
3235 int result;
3237 namebuf = alloc_printf("%s(%d)", varname, idx);
3238 if (!namebuf)
3239 return JIM_ERR;
3241 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3242 valObjPtr = Jim_NewIntObj(interp, val);
3243 if (!nameObjPtr || !valObjPtr)
3245 free(namebuf);
3246 return JIM_ERR;
3249 Jim_IncrRefCount(nameObjPtr);
3250 Jim_IncrRefCount(valObjPtr);
3251 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3252 Jim_DecrRefCount(interp, nameObjPtr);
3253 Jim_DecrRefCount(interp, valObjPtr);
3254 free(namebuf);
3255 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3256 return result;
3259 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3261 struct command_context *context;
3262 struct target *target;
3264 context = current_command_context(interp);
3265 assert (context != NULL);
3267 target = get_current_target(context);
3268 if (target == NULL)
3270 LOG_ERROR("mem2array: no current target");
3271 return JIM_ERR;
3274 return target_mem2array(interp, target, argc-1, argv + 1);
3277 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3279 long l;
3280 uint32_t width;
3281 int len;
3282 uint32_t addr;
3283 uint32_t count;
3284 uint32_t v;
3285 const char *varname;
3286 int n, e, retval;
3287 uint32_t i;
3289 /* argv[1] = name of array to receive the data
3290 * argv[2] = desired width
3291 * argv[3] = memory address
3292 * argv[4] = count of times to read
3294 if (argc != 4) {
3295 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3296 return JIM_ERR;
3298 varname = Jim_GetString(argv[0], &len);
3299 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3301 e = Jim_GetLong(interp, argv[1], &l);
3302 width = l;
3303 if (e != JIM_OK) {
3304 return e;
3307 e = Jim_GetLong(interp, argv[2], &l);
3308 addr = l;
3309 if (e != JIM_OK) {
3310 return e;
3312 e = Jim_GetLong(interp, argv[3], &l);
3313 len = l;
3314 if (e != JIM_OK) {
3315 return e;
3317 switch (width) {
3318 case 8:
3319 width = 1;
3320 break;
3321 case 16:
3322 width = 2;
3323 break;
3324 case 32:
3325 width = 4;
3326 break;
3327 default:
3328 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3329 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3330 return JIM_ERR;
3332 if (len == 0) {
3333 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3334 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3335 return JIM_ERR;
3337 if ((addr + (len * width)) < addr) {
3338 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3339 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3340 return JIM_ERR;
3342 /* absurd transfer size? */
3343 if (len > 65536) {
3344 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3345 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3346 return JIM_ERR;
3349 if ((width == 1) ||
3350 ((width == 2) && ((addr & 1) == 0)) ||
3351 ((width == 4) && ((addr & 3) == 0))) {
3352 /* all is well */
3353 } else {
3354 char buf[100];
3355 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3356 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3357 addr,
3358 width);
3359 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3360 return JIM_ERR;
3363 /* Transfer loop */
3365 /* index counter */
3366 n = 0;
3368 size_t buffersize = 4096;
3369 uint8_t *buffer = malloc(buffersize);
3370 if (buffer == NULL)
3371 return JIM_ERR;
3373 /* assume ok */
3374 e = JIM_OK;
3375 while (len) {
3376 /* Slurp... in buffer size chunks */
3378 count = len; /* in objects.. */
3379 if (count > (buffersize/width)) {
3380 count = (buffersize/width);
3383 retval = target_read_memory(target, addr, width, count, buffer);
3384 if (retval != ERROR_OK) {
3385 /* BOO !*/
3386 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3387 (unsigned int)addr,
3388 (int)width,
3389 (int)count);
3390 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3391 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3392 e = JIM_ERR;
3393 len = 0;
3394 } else {
3395 v = 0; /* shut up gcc */
3396 for (i = 0 ;i < count ;i++, n++) {
3397 switch (width) {
3398 case 4:
3399 v = target_buffer_get_u32(target, &buffer[i*width]);
3400 break;
3401 case 2:
3402 v = target_buffer_get_u16(target, &buffer[i*width]);
3403 break;
3404 case 1:
3405 v = buffer[i] & 0x0ff;
3406 break;
3408 new_int_array_element(interp, varname, n, v);
3410 len -= count;
3414 free(buffer);
3416 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3418 return JIM_OK;
3421 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3423 char *namebuf;
3424 Jim_Obj *nameObjPtr, *valObjPtr;
3425 int result;
3426 long l;
3428 namebuf = alloc_printf("%s(%d)", varname, idx);
3429 if (!namebuf)
3430 return JIM_ERR;
3432 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3433 if (!nameObjPtr)
3435 free(namebuf);
3436 return JIM_ERR;
3439 Jim_IncrRefCount(nameObjPtr);
3440 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3441 Jim_DecrRefCount(interp, nameObjPtr);
3442 free(namebuf);
3443 if (valObjPtr == NULL)
3444 return JIM_ERR;
3446 result = Jim_GetLong(interp, valObjPtr, &l);
3447 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3448 *val = l;
3449 return result;
3452 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3454 struct command_context *context;
3455 struct target *target;
3457 context = current_command_context(interp);
3458 assert (context != NULL);
3460 target = get_current_target(context);
3461 if (target == NULL) {
3462 LOG_ERROR("array2mem: no current target");
3463 return JIM_ERR;
3466 return target_array2mem(interp,target, argc-1, argv + 1);
3469 static int target_array2mem(Jim_Interp *interp, struct target *target,
3470 int argc, Jim_Obj *const *argv)
3472 long l;
3473 uint32_t width;
3474 int len;
3475 uint32_t addr;
3476 uint32_t count;
3477 uint32_t v;
3478 const char *varname;
3479 int n, e, retval;
3480 uint32_t i;
3482 /* argv[1] = name of array to get the data
3483 * argv[2] = desired width
3484 * argv[3] = memory address
3485 * argv[4] = count to write
3487 if (argc != 4) {
3488 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3489 return JIM_ERR;
3491 varname = Jim_GetString(argv[0], &len);
3492 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3494 e = Jim_GetLong(interp, argv[1], &l);
3495 width = l;
3496 if (e != JIM_OK) {
3497 return e;
3500 e = Jim_GetLong(interp, argv[2], &l);
3501 addr = l;
3502 if (e != JIM_OK) {
3503 return e;
3505 e = Jim_GetLong(interp, argv[3], &l);
3506 len = l;
3507 if (e != JIM_OK) {
3508 return e;
3510 switch (width) {
3511 case 8:
3512 width = 1;
3513 break;
3514 case 16:
3515 width = 2;
3516 break;
3517 case 32:
3518 width = 4;
3519 break;
3520 default:
3521 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3522 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3523 return JIM_ERR;
3525 if (len == 0) {
3526 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3527 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3528 return JIM_ERR;
3530 if ((addr + (len * width)) < addr) {
3531 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3532 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3533 return JIM_ERR;
3535 /* absurd transfer size? */
3536 if (len > 65536) {
3537 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3538 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3539 return JIM_ERR;
3542 if ((width == 1) ||
3543 ((width == 2) && ((addr & 1) == 0)) ||
3544 ((width == 4) && ((addr & 3) == 0))) {
3545 /* all is well */
3546 } else {
3547 char buf[100];
3548 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3549 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3550 (unsigned int)addr,
3551 (int)width);
3552 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3553 return JIM_ERR;
3556 /* Transfer loop */
3558 /* index counter */
3559 n = 0;
3560 /* assume ok */
3561 e = JIM_OK;
3563 size_t buffersize = 4096;
3564 uint8_t *buffer = malloc(buffersize);
3565 if (buffer == NULL)
3566 return JIM_ERR;
3568 while (len) {
3569 /* Slurp... in buffer size chunks */
3571 count = len; /* in objects.. */
3572 if (count > (buffersize/width)) {
3573 count = (buffersize/width);
3576 v = 0; /* shut up gcc */
3577 for (i = 0 ;i < count ;i++, n++) {
3578 get_int_array_element(interp, varname, n, &v);
3579 switch (width) {
3580 case 4:
3581 target_buffer_set_u32(target, &buffer[i*width], v);
3582 break;
3583 case 2:
3584 target_buffer_set_u16(target, &buffer[i*width], v);
3585 break;
3586 case 1:
3587 buffer[i] = v & 0x0ff;
3588 break;
3591 len -= count;
3593 retval = target_write_memory(target, addr, width, count, buffer);
3594 if (retval != ERROR_OK) {
3595 /* BOO !*/
3596 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3597 (unsigned int)addr,
3598 (int)width,
3599 (int)count);
3600 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3601 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3602 e = JIM_ERR;
3603 len = 0;
3607 free(buffer);
3609 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3611 return JIM_OK;
3614 /* FIX? should we propagate errors here rather than printing them
3615 * and continuing?
3617 void target_handle_event(struct target *target, enum target_event e)
3619 struct target_event_action *teap;
3621 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3622 if (teap->event == e) {
3623 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3624 target->target_number,
3625 target_name(target),
3626 target_type_name(target),
3628 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3629 Jim_GetString(teap->body, NULL));
3630 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3632 Jim_PrintErrorMessage(teap->interp);
3639 * Returns true only if the target has a handler for the specified event.
3641 bool target_has_event_action(struct target *target, enum target_event event)
3643 struct target_event_action *teap;
3645 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3646 if (teap->event == event)
3647 return true;
3649 return false;
3652 enum target_cfg_param {
3653 TCFG_TYPE,
3654 TCFG_EVENT,
3655 TCFG_WORK_AREA_VIRT,
3656 TCFG_WORK_AREA_PHYS,
3657 TCFG_WORK_AREA_SIZE,
3658 TCFG_WORK_AREA_BACKUP,
3659 TCFG_ENDIAN,
3660 TCFG_VARIANT,
3661 TCFG_CHAIN_POSITION,
3664 static Jim_Nvp nvp_config_opts[] = {
3665 { .name = "-type", .value = TCFG_TYPE },
3666 { .name = "-event", .value = TCFG_EVENT },
3667 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3668 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3669 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3670 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3671 { .name = "-endian" , .value = TCFG_ENDIAN },
3672 { .name = "-variant", .value = TCFG_VARIANT },
3673 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3675 { .name = NULL, .value = -1 }
3678 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3680 Jim_Nvp *n;
3681 Jim_Obj *o;
3682 jim_wide w;
3683 char *cp;
3684 int e;
3686 /* parse config or cget options ... */
3687 while (goi->argc > 0) {
3688 Jim_SetEmptyResult(goi->interp);
3689 /* Jim_GetOpt_Debug(goi); */
3691 if (target->type->target_jim_configure) {
3692 /* target defines a configure function */
3693 /* target gets first dibs on parameters */
3694 e = (*(target->type->target_jim_configure))(target, goi);
3695 if (e == JIM_OK) {
3696 /* more? */
3697 continue;
3699 if (e == JIM_ERR) {
3700 /* An error */
3701 return e;
3703 /* otherwise we 'continue' below */
3705 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3706 if (e != JIM_OK) {
3707 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3708 return e;
3710 switch (n->value) {
3711 case TCFG_TYPE:
3712 /* not setable */
3713 if (goi->isconfigure) {
3714 Jim_SetResult_sprintf(goi->interp,
3715 "not settable: %s", n->name);
3716 return JIM_ERR;
3717 } else {
3718 no_params:
3719 if (goi->argc != 0) {
3720 Jim_WrongNumArgs(goi->interp,
3721 goi->argc, goi->argv,
3722 "NO PARAMS");
3723 return JIM_ERR;
3726 Jim_SetResultString(goi->interp,
3727 target_type_name(target), -1);
3728 /* loop for more */
3729 break;
3730 case TCFG_EVENT:
3731 if (goi->argc == 0) {
3732 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3733 return JIM_ERR;
3736 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3737 if (e != JIM_OK) {
3738 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3739 return e;
3742 if (goi->isconfigure) {
3743 if (goi->argc != 1) {
3744 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3745 return JIM_ERR;
3747 } else {
3748 if (goi->argc != 0) {
3749 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3750 return JIM_ERR;
3755 struct target_event_action *teap;
3757 teap = target->event_action;
3758 /* replace existing? */
3759 while (teap) {
3760 if (teap->event == (enum target_event)n->value) {
3761 break;
3763 teap = teap->next;
3766 if (goi->isconfigure) {
3767 bool replace = true;
3768 if (teap == NULL) {
3769 /* create new */
3770 teap = calloc(1, sizeof(*teap));
3771 replace = false;
3773 teap->event = n->value;
3774 teap->interp = goi->interp;
3775 Jim_GetOpt_Obj(goi, &o);
3776 if (teap->body) {
3777 Jim_DecrRefCount(teap->interp, teap->body);
3779 teap->body = Jim_DuplicateObj(goi->interp, o);
3781 * FIXME:
3782 * Tcl/TK - "tk events" have a nice feature.
3783 * See the "BIND" command.
3784 * We should support that here.
3785 * You can specify %X and %Y in the event code.
3786 * The idea is: %T - target name.
3787 * The idea is: %N - target number
3788 * The idea is: %E - event name.
3790 Jim_IncrRefCount(teap->body);
3792 if (!replace)
3794 /* add to head of event list */
3795 teap->next = target->event_action;
3796 target->event_action = teap;
3798 Jim_SetEmptyResult(goi->interp);
3799 } else {
3800 /* get */
3801 if (teap == NULL) {
3802 Jim_SetEmptyResult(goi->interp);
3803 } else {
3804 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3808 /* loop for more */
3809 break;
3811 case TCFG_WORK_AREA_VIRT:
3812 if (goi->isconfigure) {
3813 target_free_all_working_areas(target);
3814 e = Jim_GetOpt_Wide(goi, &w);
3815 if (e != JIM_OK) {
3816 return e;
3818 target->working_area_virt = w;
3819 target->working_area_virt_spec = true;
3820 } else {
3821 if (goi->argc != 0) {
3822 goto no_params;
3825 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3826 /* loop for more */
3827 break;
3829 case TCFG_WORK_AREA_PHYS:
3830 if (goi->isconfigure) {
3831 target_free_all_working_areas(target);
3832 e = Jim_GetOpt_Wide(goi, &w);
3833 if (e != JIM_OK) {
3834 return e;
3836 target->working_area_phys = w;
3837 target->working_area_phys_spec = true;
3838 } else {
3839 if (goi->argc != 0) {
3840 goto no_params;
3843 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3844 /* loop for more */
3845 break;
3847 case TCFG_WORK_AREA_SIZE:
3848 if (goi->isconfigure) {
3849 target_free_all_working_areas(target);
3850 e = Jim_GetOpt_Wide(goi, &w);
3851 if (e != JIM_OK) {
3852 return e;
3854 target->working_area_size = w;
3855 } else {
3856 if (goi->argc != 0) {
3857 goto no_params;
3860 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3861 /* loop for more */
3862 break;
3864 case TCFG_WORK_AREA_BACKUP:
3865 if (goi->isconfigure) {
3866 target_free_all_working_areas(target);
3867 e = Jim_GetOpt_Wide(goi, &w);
3868 if (e != JIM_OK) {
3869 return e;
3871 /* make this exactly 1 or 0 */
3872 target->backup_working_area = (!!w);
3873 } else {
3874 if (goi->argc != 0) {
3875 goto no_params;
3878 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3879 /* loop for more e*/
3880 break;
3882 case TCFG_ENDIAN:
3883 if (goi->isconfigure) {
3884 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3885 if (e != JIM_OK) {
3886 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3887 return e;
3889 target->endianness = n->value;
3890 } else {
3891 if (goi->argc != 0) {
3892 goto no_params;
3895 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3896 if (n->name == NULL) {
3897 target->endianness = TARGET_LITTLE_ENDIAN;
3898 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3900 Jim_SetResultString(goi->interp, n->name, -1);
3901 /* loop for more */
3902 break;
3904 case TCFG_VARIANT:
3905 if (goi->isconfigure) {
3906 if (goi->argc < 1) {
3907 Jim_SetResult_sprintf(goi->interp,
3908 "%s ?STRING?",
3909 n->name);
3910 return JIM_ERR;
3912 if (target->variant) {
3913 free((void *)(target->variant));
3915 e = Jim_GetOpt_String(goi, &cp, NULL);
3916 target->variant = strdup(cp);
3917 } else {
3918 if (goi->argc != 0) {
3919 goto no_params;
3922 Jim_SetResultString(goi->interp, target->variant,-1);
3923 /* loop for more */
3924 break;
3925 case TCFG_CHAIN_POSITION:
3926 if (goi->isconfigure) {
3927 Jim_Obj *o_t;
3928 struct jtag_tap *tap;
3929 target_free_all_working_areas(target);
3930 e = Jim_GetOpt_Obj(goi, &o_t);
3931 if (e != JIM_OK) {
3932 return e;
3934 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
3935 if (tap == NULL) {
3936 return JIM_ERR;
3938 /* make this exactly 1 or 0 */
3939 target->tap = tap;
3940 } else {
3941 if (goi->argc != 0) {
3942 goto no_params;
3945 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
3946 /* loop for more e*/
3947 break;
3949 } /* while (goi->argc) */
3952 /* done - we return */
3953 return JIM_OK;
3956 static int
3957 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3959 Jim_GetOptInfo goi;
3961 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3962 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
3963 int need_args = 1 + goi.isconfigure;
3964 if (goi.argc < need_args)
3966 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
3967 goi.isconfigure
3968 ? "missing: -option VALUE ..."
3969 : "missing: -option ...");
3970 return JIM_ERR;
3972 struct target *target = Jim_CmdPrivData(goi.interp);
3973 return target_configure(&goi, target);
3976 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3978 const char *cmd_name = Jim_GetString(argv[0], NULL);
3980 Jim_GetOptInfo goi;
3981 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3983 if (goi.argc < 2 || goi.argc > 4)
3985 Jim_SetResult_sprintf(goi.interp,
3986 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
3987 return JIM_ERR;
3990 target_write_fn fn;
3991 fn = target_write_memory_fast;
3993 int e;
3994 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
3996 /* consume it */
3997 struct Jim_Obj *obj;
3998 e = Jim_GetOpt_Obj(&goi, &obj);
3999 if (e != JIM_OK)
4000 return e;
4002 fn = target_write_phys_memory;
4005 jim_wide a;
4006 e = Jim_GetOpt_Wide(&goi, &a);
4007 if (e != JIM_OK)
4008 return e;
4010 jim_wide b;
4011 e = Jim_GetOpt_Wide(&goi, &b);
4012 if (e != JIM_OK)
4013 return e;
4015 jim_wide c = 1;
4016 if (goi.argc == 1)
4018 e = Jim_GetOpt_Wide(&goi, &c);
4019 if (e != JIM_OK)
4020 return e;
4023 /* all args must be consumed */
4024 if (goi.argc != 0)
4026 return JIM_ERR;
4029 struct target *target = Jim_CmdPrivData(goi.interp);
4030 unsigned data_size;
4031 if (strcasecmp(cmd_name, "mww") == 0) {
4032 data_size = 4;
4034 else if (strcasecmp(cmd_name, "mwh") == 0) {
4035 data_size = 2;
4037 else if (strcasecmp(cmd_name, "mwb") == 0) {
4038 data_size = 1;
4039 } else {
4040 LOG_ERROR("command '%s' unknown: ", cmd_name);
4041 return JIM_ERR;
4044 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4047 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4049 const char *cmd_name = Jim_GetString(argv[0], NULL);
4051 Jim_GetOptInfo goi;
4052 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4054 if ((goi.argc < 1) || (goi.argc > 3))
4056 Jim_SetResult_sprintf(goi.interp,
4057 "usage: %s [phys] <address> [<count>]", cmd_name);
4058 return JIM_ERR;
4061 int (*fn)(struct target *target,
4062 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4063 fn=target_read_memory;
4065 int e;
4066 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4068 /* consume it */
4069 struct Jim_Obj *obj;
4070 e = Jim_GetOpt_Obj(&goi, &obj);
4071 if (e != JIM_OK)
4072 return e;
4074 fn=target_read_phys_memory;
4077 jim_wide a;
4078 e = Jim_GetOpt_Wide(&goi, &a);
4079 if (e != JIM_OK) {
4080 return JIM_ERR;
4082 jim_wide c;
4083 if (goi.argc == 1) {
4084 e = Jim_GetOpt_Wide(&goi, &c);
4085 if (e != JIM_OK) {
4086 return JIM_ERR;
4088 } else {
4089 c = 1;
4092 /* all args must be consumed */
4093 if (goi.argc != 0)
4095 return JIM_ERR;
4098 jim_wide b = 1; /* shut up gcc */
4099 if (strcasecmp(cmd_name, "mdw") == 0)
4100 b = 4;
4101 else if (strcasecmp(cmd_name, "mdh") == 0)
4102 b = 2;
4103 else if (strcasecmp(cmd_name, "mdb") == 0)
4104 b = 1;
4105 else {
4106 LOG_ERROR("command '%s' unknown: ", cmd_name);
4107 return JIM_ERR;
4110 /* convert count to "bytes" */
4111 c = c * b;
4113 struct target *target = Jim_CmdPrivData(goi.interp);
4114 uint8_t target_buf[32];
4115 jim_wide x, y, z;
4116 while (c > 0) {
4117 y = c;
4118 if (y > 16) {
4119 y = 16;
4121 e = fn(target, a, b, y / b, target_buf);
4122 if (e != ERROR_OK) {
4123 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4124 return JIM_ERR;
4127 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4128 switch (b) {
4129 case 4:
4130 for (x = 0; x < 16 && x < y; x += 4)
4132 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4133 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4135 for (; (x < 16) ; x += 4) {
4136 Jim_fprintf(interp, interp->cookie_stdout, " ");
4138 break;
4139 case 2:
4140 for (x = 0; x < 16 && x < y; x += 2)
4142 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4143 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4145 for (; (x < 16) ; x += 2) {
4146 Jim_fprintf(interp, interp->cookie_stdout, " ");
4148 break;
4149 case 1:
4150 default:
4151 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4152 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4153 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4155 for (; (x < 16) ; x += 1) {
4156 Jim_fprintf(interp, interp->cookie_stdout, " ");
4158 break;
4160 /* ascii-ify the bytes */
4161 for (x = 0 ; x < y ; x++) {
4162 if ((target_buf[x] >= 0x20) &&
4163 (target_buf[x] <= 0x7e)) {
4164 /* good */
4165 } else {
4166 /* smack it */
4167 target_buf[x] = '.';
4170 /* space pad */
4171 while (x < 16) {
4172 target_buf[x] = ' ';
4173 x++;
4175 /* terminate */
4176 target_buf[16] = 0;
4177 /* print - with a newline */
4178 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4179 /* NEXT... */
4180 c -= 16;
4181 a += 16;
4183 return JIM_OK;
4186 static int jim_target_mem2array(Jim_Interp *interp,
4187 int argc, Jim_Obj *const *argv)
4189 struct target *target = Jim_CmdPrivData(interp);
4190 return target_mem2array(interp, target, argc - 1, argv + 1);
4193 static int jim_target_array2mem(Jim_Interp *interp,
4194 int argc, Jim_Obj *const *argv)
4196 struct target *target = Jim_CmdPrivData(interp);
4197 return target_array2mem(interp, target, argc - 1, argv + 1);
4200 static int jim_target_tap_disabled(Jim_Interp *interp)
4202 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4203 return JIM_ERR;
4206 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4208 if (argc != 1)
4210 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4211 return JIM_ERR;
4213 struct target *target = Jim_CmdPrivData(interp);
4214 if (!target->tap->enabled)
4215 return jim_target_tap_disabled(interp);
4217 int e = target->type->examine(target);
4218 if (e != ERROR_OK)
4220 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4221 return JIM_ERR;
4223 return JIM_OK;
4226 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4228 if (argc != 1)
4230 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4231 return JIM_ERR;
4233 struct target *target = Jim_CmdPrivData(interp);
4235 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4236 return JIM_ERR;
4238 return JIM_OK;
4241 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4243 if (argc != 1)
4245 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4246 return JIM_ERR;
4248 struct target *target = Jim_CmdPrivData(interp);
4249 if (!target->tap->enabled)
4250 return jim_target_tap_disabled(interp);
4252 int e;
4253 if (!(target_was_examined(target))) {
4254 e = ERROR_TARGET_NOT_EXAMINED;
4255 } else {
4256 e = target->type->poll(target);
4258 if (e != ERROR_OK)
4260 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4261 return JIM_ERR;
4263 return JIM_OK;
4266 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4268 Jim_GetOptInfo goi;
4269 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4271 if (goi.argc != 2)
4273 Jim_WrongNumArgs(interp, 0, argv,
4274 "([tT]|[fF]|assert|deassert) BOOL");
4275 return JIM_ERR;
4278 Jim_Nvp *n;
4279 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4280 if (e != JIM_OK)
4282 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4283 return e;
4285 /* the halt or not param */
4286 jim_wide a;
4287 e = Jim_GetOpt_Wide(&goi, &a);
4288 if (e != JIM_OK)
4289 return e;
4291 struct target *target = Jim_CmdPrivData(goi.interp);
4292 if (!target->tap->enabled)
4293 return jim_target_tap_disabled(interp);
4294 if (!(target_was_examined(target)))
4296 LOG_ERROR("Target not examined yet");
4297 return ERROR_TARGET_NOT_EXAMINED;
4299 if (!target->type->assert_reset || !target->type->deassert_reset)
4301 Jim_SetResult_sprintf(interp,
4302 "No target-specific reset for %s",
4303 target_name(target));
4304 return JIM_ERR;
4306 /* determine if we should halt or not. */
4307 target->reset_halt = !!a;
4308 /* When this happens - all workareas are invalid. */
4309 target_free_all_working_areas_restore(target, 0);
4311 /* do the assert */
4312 if (n->value == NVP_ASSERT) {
4313 e = target->type->assert_reset(target);
4314 } else {
4315 e = target->type->deassert_reset(target);
4317 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4320 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4322 if (argc != 1) {
4323 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4324 return JIM_ERR;
4326 struct target *target = Jim_CmdPrivData(interp);
4327 if (!target->tap->enabled)
4328 return jim_target_tap_disabled(interp);
4329 int e = target->type->halt(target);
4330 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4333 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4335 Jim_GetOptInfo goi;
4336 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4338 /* params: <name> statename timeoutmsecs */
4339 if (goi.argc != 2)
4341 const char *cmd_name = Jim_GetString(argv[0], NULL);
4342 Jim_SetResult_sprintf(goi.interp,
4343 "%s <state_name> <timeout_in_msec>", cmd_name);
4344 return JIM_ERR;
4347 Jim_Nvp *n;
4348 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4349 if (e != JIM_OK) {
4350 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4351 return e;
4353 jim_wide a;
4354 e = Jim_GetOpt_Wide(&goi, &a);
4355 if (e != JIM_OK) {
4356 return e;
4358 struct target *target = Jim_CmdPrivData(interp);
4359 if (!target->tap->enabled)
4360 return jim_target_tap_disabled(interp);
4362 e = target_wait_state(target, n->value, a);
4363 if (e != ERROR_OK)
4365 Jim_SetResult_sprintf(goi.interp,
4366 "target: %s wait %s fails (%d) %s",
4367 target_name(target), n->name,
4368 e, target_strerror_safe(e));
4369 return JIM_ERR;
4371 return JIM_OK;
4373 /* List for human, Events defined for this target.
4374 * scripts/programs should use 'name cget -event NAME'
4376 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4378 struct command_context *cmd_ctx = current_command_context(interp);
4379 assert (cmd_ctx != NULL);
4381 struct target *target = Jim_CmdPrivData(interp);
4382 struct target_event_action *teap = target->event_action;
4383 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4384 target->target_number,
4385 target_name(target));
4386 command_print(cmd_ctx, "%-25s | Body", "Event");
4387 command_print(cmd_ctx, "------------------------- | "
4388 "----------------------------------------");
4389 while (teap)
4391 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4392 command_print(cmd_ctx, "%-25s | %s",
4393 opt->name, Jim_GetString(teap->body, NULL));
4394 teap = teap->next;
4396 command_print(cmd_ctx, "***END***");
4397 return JIM_OK;
4399 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4401 if (argc != 1)
4403 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4404 return JIM_ERR;
4406 struct target *target = Jim_CmdPrivData(interp);
4407 Jim_SetResultString(interp, target_state_name(target), -1);
4408 return JIM_OK;
4410 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4412 Jim_GetOptInfo goi;
4413 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4414 if (goi.argc != 1)
4416 const char *cmd_name = Jim_GetString(argv[0], NULL);
4417 Jim_SetResult_sprintf(goi.interp, "%s <eventname>", cmd_name);
4418 return JIM_ERR;
4420 Jim_Nvp *n;
4421 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4422 if (e != JIM_OK)
4424 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4425 return e;
4427 struct target *target = Jim_CmdPrivData(interp);
4428 target_handle_event(target, n->value);
4429 return JIM_OK;
4432 static const struct command_registration target_instance_command_handlers[] = {
4434 .name = "configure",
4435 .mode = COMMAND_CONFIG,
4436 .jim_handler = jim_target_configure,
4437 .help = "configure a new target for use",
4438 .usage = "[target_attribute ...]",
4441 .name = "cget",
4442 .mode = COMMAND_ANY,
4443 .jim_handler = jim_target_configure,
4444 .help = "returns the specified target attribute",
4445 .usage = "target_attribute",
4448 .name = "mww",
4449 .mode = COMMAND_EXEC,
4450 .jim_handler = jim_target_mw,
4451 .help = "Write 32-bit word(s) to target memory",
4452 .usage = "address data [count]",
4455 .name = "mwh",
4456 .mode = COMMAND_EXEC,
4457 .jim_handler = jim_target_mw,
4458 .help = "Write 16-bit half-word(s) to target memory",
4459 .usage = "address data [count]",
4462 .name = "mwb",
4463 .mode = COMMAND_EXEC,
4464 .jim_handler = jim_target_mw,
4465 .help = "Write byte(s) to target memory",
4466 .usage = "address data [count]",
4469 .name = "mdw",
4470 .mode = COMMAND_EXEC,
4471 .jim_handler = jim_target_md,
4472 .help = "Display target memory as 32-bit words",
4473 .usage = "address [count]",
4476 .name = "mdh",
4477 .mode = COMMAND_EXEC,
4478 .jim_handler = jim_target_md,
4479 .help = "Display target memory as 16-bit half-words",
4480 .usage = "address [count]",
4483 .name = "mdb",
4484 .mode = COMMAND_EXEC,
4485 .jim_handler = jim_target_md,
4486 .help = "Display target memory as 8-bit bytes",
4487 .usage = "address [count]",
4490 .name = "array2mem",
4491 .mode = COMMAND_EXEC,
4492 .jim_handler = jim_target_array2mem,
4493 .help = "Writes Tcl array of 8/16/32 bit numbers "
4494 "to target memory",
4495 .usage = "arrayname bitwidth address count",
4498 .name = "mem2array",
4499 .mode = COMMAND_EXEC,
4500 .jim_handler = jim_target_mem2array,
4501 .help = "Loads Tcl array of 8/16/32 bit numbers "
4502 "from target memory",
4503 .usage = "arrayname bitwidth address count",
4506 .name = "eventlist",
4507 .mode = COMMAND_EXEC,
4508 .jim_handler = jim_target_event_list,
4509 .help = "displays a table of events defined for this target",
4512 .name = "curstate",
4513 .mode = COMMAND_EXEC,
4514 .jim_handler = jim_target_current_state,
4515 .help = "displays the current state of this target",
4518 .name = "arp_examine",
4519 .mode = COMMAND_EXEC,
4520 .jim_handler = jim_target_examine,
4521 .help = "used internally for reset processing",
4524 .name = "arp_halt_gdb",
4525 .mode = COMMAND_EXEC,
4526 .jim_handler = jim_target_halt_gdb,
4527 .help = "used internally for reset processing to halt GDB",
4530 .name = "arp_poll",
4531 .mode = COMMAND_EXEC,
4532 .jim_handler = jim_target_poll,
4533 .help = "used internally for reset processing",
4536 .name = "arp_reset",
4537 .mode = COMMAND_EXEC,
4538 .jim_handler = jim_target_reset,
4539 .help = "used internally for reset processing",
4542 .name = "arp_halt",
4543 .mode = COMMAND_EXEC,
4544 .jim_handler = jim_target_halt,
4545 .help = "used internally for reset processing",
4548 .name = "arp_waitstate",
4549 .mode = COMMAND_EXEC,
4550 .jim_handler = jim_target_wait_state,
4551 .help = "used internally for reset processing",
4554 .name = "invoke-event",
4555 .mode = COMMAND_EXEC,
4556 .jim_handler = jim_target_invoke_event,
4557 .help = "invoke handler for specified event",
4558 .usage = "event_name",
4560 COMMAND_REGISTRATION_DONE
4563 static int target_create(Jim_GetOptInfo *goi)
4565 Jim_Obj *new_cmd;
4566 Jim_Cmd *cmd;
4567 const char *cp;
4568 char *cp2;
4569 int e;
4570 int x;
4571 struct target *target;
4572 struct command_context *cmd_ctx;
4574 cmd_ctx = current_command_context(goi->interp);
4575 assert (cmd_ctx != NULL);
4577 if (goi->argc < 3) {
4578 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4579 return JIM_ERR;
4582 /* COMMAND */
4583 Jim_GetOpt_Obj(goi, &new_cmd);
4584 /* does this command exist? */
4585 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4586 if (cmd) {
4587 cp = Jim_GetString(new_cmd, NULL);
4588 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4589 return JIM_ERR;
4592 /* TYPE */
4593 e = Jim_GetOpt_String(goi, &cp2, NULL);
4594 cp = cp2;
4595 /* now does target type exist */
4596 for (x = 0 ; target_types[x] ; x++) {
4597 if (0 == strcmp(cp, target_types[x]->name)) {
4598 /* found */
4599 break;
4602 if (target_types[x] == NULL) {
4603 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4604 for (x = 0 ; target_types[x] ; x++) {
4605 if (target_types[x + 1]) {
4606 Jim_AppendStrings(goi->interp,
4607 Jim_GetResult(goi->interp),
4608 target_types[x]->name,
4609 ", ", NULL);
4610 } else {
4611 Jim_AppendStrings(goi->interp,
4612 Jim_GetResult(goi->interp),
4613 " or ",
4614 target_types[x]->name,NULL);
4617 return JIM_ERR;
4620 /* Create it */
4621 target = calloc(1,sizeof(struct target));
4622 /* set target number */
4623 target->target_number = new_target_number();
4625 /* allocate memory for each unique target type */
4626 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4628 memcpy(target->type, target_types[x], sizeof(struct target_type));
4630 /* will be set by "-endian" */
4631 target->endianness = TARGET_ENDIAN_UNKNOWN;
4633 target->working_area = 0x0;
4634 target->working_area_size = 0x0;
4635 target->working_areas = NULL;
4636 target->backup_working_area = 0;
4638 target->state = TARGET_UNKNOWN;
4639 target->debug_reason = DBG_REASON_UNDEFINED;
4640 target->reg_cache = NULL;
4641 target->breakpoints = NULL;
4642 target->watchpoints = NULL;
4643 target->next = NULL;
4644 target->arch_info = NULL;
4646 target->display = 1;
4648 target->halt_issued = false;
4650 /* initialize trace information */
4651 target->trace_info = malloc(sizeof(struct trace));
4652 target->trace_info->num_trace_points = 0;
4653 target->trace_info->trace_points_size = 0;
4654 target->trace_info->trace_points = NULL;
4655 target->trace_info->trace_history_size = 0;
4656 target->trace_info->trace_history = NULL;
4657 target->trace_info->trace_history_pos = 0;
4658 target->trace_info->trace_history_overflowed = 0;
4660 target->dbgmsg = NULL;
4661 target->dbg_msg_enabled = 0;
4663 target->endianness = TARGET_ENDIAN_UNKNOWN;
4665 /* Do the rest as "configure" options */
4666 goi->isconfigure = 1;
4667 e = target_configure(goi, target);
4669 if (target->tap == NULL)
4671 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4672 e = JIM_ERR;
4675 if (e != JIM_OK) {
4676 free(target->type);
4677 free(target);
4678 return e;
4681 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4682 /* default endian to little if not specified */
4683 target->endianness = TARGET_LITTLE_ENDIAN;
4686 /* incase variant is not set */
4687 if (!target->variant)
4688 target->variant = strdup("");
4690 cp = Jim_GetString(new_cmd, NULL);
4691 target->cmd_name = strdup(cp);
4693 /* create the target specific commands */
4694 if (target->type->commands) {
4695 e = register_commands(cmd_ctx, NULL, target->type->commands);
4696 if (ERROR_OK != e)
4697 LOG_ERROR("unable to register '%s' commands", cp);
4699 if (target->type->target_create) {
4700 (*(target->type->target_create))(target, goi->interp);
4703 /* append to end of list */
4705 struct target **tpp;
4706 tpp = &(all_targets);
4707 while (*tpp) {
4708 tpp = &((*tpp)->next);
4710 *tpp = target;
4713 /* now - create the new target name command */
4714 const const struct command_registration target_subcommands[] = {
4716 .chain = target_instance_command_handlers,
4719 .chain = target->type->commands,
4721 COMMAND_REGISTRATION_DONE
4723 const const struct command_registration target_commands[] = {
4725 .name = cp,
4726 .mode = COMMAND_ANY,
4727 .help = "target command group",
4728 .chain = target_subcommands,
4730 COMMAND_REGISTRATION_DONE
4732 e = register_commands(cmd_ctx, NULL, target_commands);
4733 if (ERROR_OK != e)
4734 return JIM_ERR;
4736 struct command *c = command_find_in_context(cmd_ctx, cp);
4737 assert(c);
4738 command_set_handler_data(c, target);
4740 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4743 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4745 if (argc != 1)
4747 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4748 return JIM_ERR;
4750 struct command_context *cmd_ctx = current_command_context(interp);
4751 assert (cmd_ctx != NULL);
4753 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4754 return JIM_OK;
4757 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4759 if (argc != 1)
4761 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4762 return JIM_ERR;
4764 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4765 for (unsigned x = 0; NULL != target_types[x]; x++)
4767 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4768 Jim_NewStringObj(interp, target_types[x]->name, -1));
4770 return JIM_OK;
4773 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4775 if (argc != 1)
4777 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4778 return JIM_ERR;
4780 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4781 struct target *target = all_targets;
4782 while (target)
4784 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4785 Jim_NewStringObj(interp, target_name(target), -1));
4786 target = target->next;
4788 return JIM_OK;
4791 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4793 Jim_GetOptInfo goi;
4794 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4795 if (goi.argc < 3)
4797 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4798 "<name> <target_type> [<target_options> ...]");
4799 return JIM_ERR;
4801 return target_create(&goi);
4804 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4806 Jim_GetOptInfo goi;
4807 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4809 /* It's OK to remove this mechanism sometime after August 2010 or so */
4810 LOG_WARNING("don't use numbers as target identifiers; use names");
4811 if (goi.argc != 1)
4813 Jim_SetResult_sprintf(goi.interp, "usage: target number <number>");
4814 return JIM_ERR;
4816 jim_wide w;
4817 int e = Jim_GetOpt_Wide(&goi, &w);
4818 if (e != JIM_OK)
4819 return JIM_ERR;
4821 struct target *target;
4822 for (target = all_targets; NULL != target; target = target->next)
4824 if (target->target_number != w)
4825 continue;
4827 Jim_SetResultString(goi.interp, target_name(target), -1);
4828 return JIM_OK;
4830 Jim_SetResult_sprintf(goi.interp,
4831 "Target: number %d does not exist", (int)(w));
4832 return JIM_ERR;
4835 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4837 if (argc != 1)
4839 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4840 return JIM_ERR;
4842 unsigned count = 0;
4843 struct target *target = all_targets;
4844 while (NULL != target)
4846 target = target->next;
4847 count++;
4849 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4850 return JIM_OK;
4853 static const struct command_registration target_subcommand_handlers[] = {
4855 .name = "init",
4856 .mode = COMMAND_CONFIG,
4857 .handler = handle_target_init_command,
4858 .help = "initialize targets",
4861 .name = "create",
4862 /* REVISIT this should be COMMAND_CONFIG ... */
4863 .mode = COMMAND_ANY,
4864 .jim_handler = jim_target_create,
4865 .usage = "name type '-chain-position' name [options ...]",
4866 .help = "Creates and selects a new target",
4869 .name = "current",
4870 .mode = COMMAND_ANY,
4871 .jim_handler = jim_target_current,
4872 .help = "Returns the currently selected target",
4875 .name = "types",
4876 .mode = COMMAND_ANY,
4877 .jim_handler = jim_target_types,
4878 .help = "Returns the available target types as "
4879 "a list of strings",
4882 .name = "names",
4883 .mode = COMMAND_ANY,
4884 .jim_handler = jim_target_names,
4885 .help = "Returns the names of all targets as a list of strings",
4888 .name = "number",
4889 .mode = COMMAND_ANY,
4890 .jim_handler = jim_target_number,
4891 .usage = "number",
4892 .help = "Returns the name of the numbered target "
4893 "(DEPRECATED)",
4896 .name = "count",
4897 .mode = COMMAND_ANY,
4898 .jim_handler = jim_target_count,
4899 .help = "Returns the number of targets as an integer "
4900 "(DEPRECATED)",
4902 COMMAND_REGISTRATION_DONE
4905 struct FastLoad
4907 uint32_t address;
4908 uint8_t *data;
4909 int length;
4913 static int fastload_num;
4914 static struct FastLoad *fastload;
4916 static void free_fastload(void)
4918 if (fastload != NULL)
4920 int i;
4921 for (i = 0; i < fastload_num; i++)
4923 if (fastload[i].data)
4924 free(fastload[i].data);
4926 free(fastload);
4927 fastload = NULL;
4934 COMMAND_HANDLER(handle_fast_load_image_command)
4936 uint8_t *buffer;
4937 size_t buf_cnt;
4938 uint32_t image_size;
4939 uint32_t min_address = 0;
4940 uint32_t max_address = 0xffffffff;
4941 int i;
4943 struct image image;
4945 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4946 &image, &min_address, &max_address);
4947 if (ERROR_OK != retval)
4948 return retval;
4950 struct duration bench;
4951 duration_start(&bench);
4953 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
4955 return ERROR_OK;
4958 image_size = 0x0;
4959 retval = ERROR_OK;
4960 fastload_num = image.num_sections;
4961 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4962 if (fastload == NULL)
4964 image_close(&image);
4965 return ERROR_FAIL;
4967 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4968 for (i = 0; i < image.num_sections; i++)
4970 buffer = malloc(image.sections[i].size);
4971 if (buffer == NULL)
4973 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
4974 (int)(image.sections[i].size));
4975 break;
4978 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4980 free(buffer);
4981 break;
4984 uint32_t offset = 0;
4985 uint32_t length = buf_cnt;
4988 /* DANGER!!! beware of unsigned comparision here!!! */
4990 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4991 (image.sections[i].base_address < max_address))
4993 if (image.sections[i].base_address < min_address)
4995 /* clip addresses below */
4996 offset += min_address-image.sections[i].base_address;
4997 length -= offset;
5000 if (image.sections[i].base_address + buf_cnt > max_address)
5002 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5005 fastload[i].address = image.sections[i].base_address + offset;
5006 fastload[i].data = malloc(length);
5007 if (fastload[i].data == NULL)
5009 free(buffer);
5010 break;
5012 memcpy(fastload[i].data, buffer + offset, length);
5013 fastload[i].length = length;
5015 image_size += length;
5016 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5017 (unsigned int)length,
5018 ((unsigned int)(image.sections[i].base_address + offset)));
5021 free(buffer);
5024 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5026 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5027 "in %fs (%0.3f KiB/s)", image_size,
5028 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5030 command_print(CMD_CTX,
5031 "WARNING: image has not been loaded to target!"
5032 "You can issue a 'fast_load' to finish loading.");
5035 image_close(&image);
5037 if (retval != ERROR_OK)
5039 free_fastload();
5042 return retval;
5045 COMMAND_HANDLER(handle_fast_load_command)
5047 if (CMD_ARGC > 0)
5048 return ERROR_COMMAND_SYNTAX_ERROR;
5049 if (fastload == NULL)
5051 LOG_ERROR("No image in memory");
5052 return ERROR_FAIL;
5054 int i;
5055 int ms = timeval_ms();
5056 int size = 0;
5057 int retval = ERROR_OK;
5058 for (i = 0; i < fastload_num;i++)
5060 struct target *target = get_current_target(CMD_CTX);
5061 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5062 (unsigned int)(fastload[i].address),
5063 (unsigned int)(fastload[i].length));
5064 if (retval == ERROR_OK)
5066 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5068 size += fastload[i].length;
5070 int after = timeval_ms();
5071 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5072 return retval;
5075 static const struct command_registration target_command_handlers[] = {
5077 .name = "targets",
5078 .handler = handle_targets_command,
5079 .mode = COMMAND_ANY,
5080 .help = "change current default target (one parameter) "
5081 "or prints table of all targets (no parameters)",
5082 .usage = "[target]",
5085 .name = "target",
5086 .mode = COMMAND_CONFIG,
5087 .help = "configure target",
5089 .chain = target_subcommand_handlers,
5091 COMMAND_REGISTRATION_DONE
5094 int target_register_commands(struct command_context *cmd_ctx)
5096 return register_commands(cmd_ctx, NULL, target_command_handlers);
5099 static bool target_reset_nag = true;
5101 bool get_target_reset_nag(void)
5103 return target_reset_nag;
5106 COMMAND_HANDLER(handle_target_reset_nag)
5108 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5109 &target_reset_nag, "Nag after each reset about options to improve "
5110 "performance");
5113 static const struct command_registration target_exec_command_handlers[] = {
5115 .name = "fast_load_image",
5116 .handler = handle_fast_load_image_command,
5117 .mode = COMMAND_ANY,
5118 .help = "Load image into server memory for later use by "
5119 "fast_load; primarily for profiling",
5120 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5121 "[min_address [max_length]]",
5124 .name = "fast_load",
5125 .handler = handle_fast_load_command,
5126 .mode = COMMAND_EXEC,
5127 .help = "loads active fast load image to current target "
5128 "- mainly for profiling purposes",
5131 .name = "profile",
5132 .handler = handle_profile_command,
5133 .mode = COMMAND_EXEC,
5134 .help = "profiling samples the CPU PC",
5136 /** @todo don't register virt2phys() unless target supports it */
5138 .name = "virt2phys",
5139 .handler = handle_virt2phys_command,
5140 .mode = COMMAND_ANY,
5141 .help = "translate a virtual address into a physical address",
5142 .usage = "virtual_address",
5145 .name = "reg",
5146 .handler = handle_reg_command,
5147 .mode = COMMAND_EXEC,
5148 .help = "display or set a register; with no arguments, "
5149 "displays all registers and their values",
5150 .usage = "[(register_name|register_number) [value]]",
5153 .name = "poll",
5154 .handler = handle_poll_command,
5155 .mode = COMMAND_EXEC,
5156 .help = "poll target state; or reconfigure background polling",
5157 .usage = "['on'|'off']",
5160 .name = "wait_halt",
5161 .handler = handle_wait_halt_command,
5162 .mode = COMMAND_EXEC,
5163 .help = "wait up to the specified number of milliseconds "
5164 "(default 5) for a previously requested halt",
5165 .usage = "[milliseconds]",
5168 .name = "halt",
5169 .handler = handle_halt_command,
5170 .mode = COMMAND_EXEC,
5171 .help = "request target to halt, then wait up to the specified"
5172 "number of milliseconds (default 5) for it to complete",
5173 .usage = "[milliseconds]",
5176 .name = "resume",
5177 .handler = handle_resume_command,
5178 .mode = COMMAND_EXEC,
5179 .help = "resume target execution from current PC or address",
5180 .usage = "[address]",
5183 .name = "reset",
5184 .handler = handle_reset_command,
5185 .mode = COMMAND_EXEC,
5186 .usage = "[run|halt|init]",
5187 .help = "Reset all targets into the specified mode."
5188 "Default reset mode is run, if not given.",
5191 .name = "soft_reset_halt",
5192 .handler = handle_soft_reset_halt_command,
5193 .mode = COMMAND_EXEC,
5194 .help = "halt the target and do a soft reset",
5197 .name = "step",
5198 .handler = handle_step_command,
5199 .mode = COMMAND_EXEC,
5200 .help = "step one instruction from current PC or address",
5201 .usage = "[address]",
5204 .name = "mdw",
5205 .handler = handle_md_command,
5206 .mode = COMMAND_EXEC,
5207 .help = "display memory words",
5208 .usage = "['phys'] address [count]",
5211 .name = "mdh",
5212 .handler = handle_md_command,
5213 .mode = COMMAND_EXEC,
5214 .help = "display memory half-words",
5215 .usage = "['phys'] address [count]",
5218 .name = "mdb",
5219 .handler = handle_md_command,
5220 .mode = COMMAND_EXEC,
5221 .help = "display memory bytes",
5222 .usage = "['phys'] address [count]",
5225 .name = "mww",
5226 .handler = handle_mw_command,
5227 .mode = COMMAND_EXEC,
5228 .help = "write memory word",
5229 .usage = "['phys'] address value [count]",
5232 .name = "mwh",
5233 .handler = handle_mw_command,
5234 .mode = COMMAND_EXEC,
5235 .help = "write memory half-word",
5236 .usage = "['phys'] address value [count]",
5239 .name = "mwb",
5240 .handler = handle_mw_command,
5241 .mode = COMMAND_EXEC,
5242 .help = "write memory byte",
5243 .usage = "['phys'] address value [count]",
5246 .name = "bp",
5247 .handler = handle_bp_command,
5248 .mode = COMMAND_EXEC,
5249 .help = "list or set hardware or software breakpoint",
5250 .usage = "[address length ['hw']]",
5253 .name = "rbp",
5254 .handler = handle_rbp_command,
5255 .mode = COMMAND_EXEC,
5256 .help = "remove breakpoint",
5257 .usage = "address",
5260 .name = "wp",
5261 .handler = handle_wp_command,
5262 .mode = COMMAND_EXEC,
5263 .help = "list (no params) or create watchpoints",
5264 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5267 .name = "rwp",
5268 .handler = handle_rwp_command,
5269 .mode = COMMAND_EXEC,
5270 .help = "remove watchpoint",
5271 .usage = "address",
5274 .name = "load_image",
5275 .handler = handle_load_image_command,
5276 .mode = COMMAND_EXEC,
5277 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5278 "[min_address] [max_length]",
5281 .name = "dump_image",
5282 .handler = handle_dump_image_command,
5283 .mode = COMMAND_EXEC,
5284 .usage = "filename address size",
5287 .name = "verify_image",
5288 .handler = handle_verify_image_command,
5289 .mode = COMMAND_EXEC,
5290 .usage = "filename [offset [type]]",
5293 .name = "test_image",
5294 .handler = handle_test_image_command,
5295 .mode = COMMAND_EXEC,
5296 .usage = "filename [offset [type]]",
5299 .name = "mem2array",
5300 .mode = COMMAND_EXEC,
5301 .jim_handler = jim_mem2array,
5302 .help = "read 8/16/32 bit memory and return as a TCL array "
5303 "for script processing",
5304 .usage = "arrayname bitwidth address count",
5307 .name = "array2mem",
5308 .mode = COMMAND_EXEC,
5309 .jim_handler = jim_array2mem,
5310 .help = "convert a TCL array to memory locations "
5311 "and write the 8/16/32 bit values",
5312 .usage = "arrayname bitwidth address count",
5315 .name = "reset_nag",
5316 .handler = handle_target_reset_nag,
5317 .mode = COMMAND_ANY,
5318 .help = "Nag after each reset about options that could have been "
5319 "enabled to improve performance. ",
5320 .usage = "['enable'|'disable']",
5322 COMMAND_REGISTRATION_DONE
5324 static int target_register_user_commands(struct command_context *cmd_ctx)
5326 int retval = ERROR_OK;
5327 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5328 return retval;
5330 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5331 return retval;
5334 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);