TARGET: fix segfault in handle_dump_image_command()
[openocd.git] / src / target / target.c
blob3c85502e903a0161e9a804d8b1d61075ff75c755
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;
73 extern struct target_type avr32_ap7k_target;
75 static struct target_type *target_types[] =
77 &arm7tdmi_target,
78 &arm9tdmi_target,
79 &arm920t_target,
80 &arm720t_target,
81 &arm966e_target,
82 &arm926ejs_target,
83 &fa526_target,
84 &feroceon_target,
85 &dragonite_target,
86 &xscale_target,
87 &cortexm3_target,
88 &cortexa8_target,
89 &arm11_target,
90 &mips_m4k_target,
91 &avr_target,
92 &dsp563xx_target,
93 &testee_target,
94 &avr32_ap7k_target,
95 NULL,
98 struct target *all_targets = NULL;
99 static struct target_event_callback *target_event_callbacks = NULL;
100 static struct target_timer_callback *target_timer_callbacks = NULL;
101 static const int polling_interval = 100;
103 static const Jim_Nvp nvp_assert[] = {
104 { .name = "assert", NVP_ASSERT },
105 { .name = "deassert", NVP_DEASSERT },
106 { .name = "T", NVP_ASSERT },
107 { .name = "F", NVP_DEASSERT },
108 { .name = "t", NVP_ASSERT },
109 { .name = "f", NVP_DEASSERT },
110 { .name = NULL, .value = -1 }
113 static const Jim_Nvp nvp_error_target[] = {
114 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
115 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
116 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
117 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
118 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
119 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
120 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
121 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
122 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
123 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
124 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
125 { .value = -1, .name = NULL }
128 static const char *target_strerror_safe(int err)
130 const Jim_Nvp *n;
132 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
133 if (n->name == NULL) {
134 return "unknown";
135 } else {
136 return n->name;
140 static const Jim_Nvp nvp_target_event[] = {
141 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
142 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
144 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
145 { .value = TARGET_EVENT_HALTED, .name = "halted" },
146 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
147 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
148 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
150 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
151 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
153 /* historical name */
155 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
157 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
158 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
159 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
160 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
161 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
162 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
163 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
164 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
165 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
166 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
167 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
169 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
170 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
172 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
173 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
175 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
176 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
178 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
179 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
181 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
182 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
184 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
185 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
186 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
188 { .name = NULL, .value = -1 }
191 static const Jim_Nvp nvp_target_state[] = {
192 { .name = "unknown", .value = TARGET_UNKNOWN },
193 { .name = "running", .value = TARGET_RUNNING },
194 { .name = "halted", .value = TARGET_HALTED },
195 { .name = "reset", .value = TARGET_RESET },
196 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
197 { .name = NULL, .value = -1 },
200 static const Jim_Nvp nvp_target_debug_reason [] = {
201 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
202 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
203 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
204 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
205 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
206 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
207 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
208 { .name = NULL, .value = -1 },
211 static const Jim_Nvp nvp_target_endian[] = {
212 { .name = "big", .value = TARGET_BIG_ENDIAN },
213 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
214 { .name = "be", .value = TARGET_BIG_ENDIAN },
215 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
216 { .name = NULL, .value = -1 },
219 static const Jim_Nvp nvp_reset_modes[] = {
220 { .name = "unknown", .value = RESET_UNKNOWN },
221 { .name = "run" , .value = RESET_RUN },
222 { .name = "halt" , .value = RESET_HALT },
223 { .name = "init" , .value = RESET_INIT },
224 { .name = NULL , .value = -1 },
227 const char *debug_reason_name(struct target *t)
229 const char *cp;
231 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
232 t->debug_reason)->name;
233 if (!cp) {
234 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
235 cp = "(*BUG*unknown*BUG*)";
237 return cp;
240 const char *
241 target_state_name( struct target *t )
243 const char *cp;
244 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
245 if( !cp ){
246 LOG_ERROR("Invalid target state: %d", (int)(t->state));
247 cp = "(*BUG*unknown*BUG*)";
249 return cp;
252 /* determine the number of the new target */
253 static int new_target_number(void)
255 struct target *t;
256 int x;
258 /* number is 0 based */
259 x = -1;
260 t = all_targets;
261 while (t) {
262 if (x < t->target_number) {
263 x = t->target_number;
265 t = t->next;
267 return x + 1;
270 /* read a uint32_t from a buffer in target memory endianness */
271 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
273 if (target->endianness == TARGET_LITTLE_ENDIAN)
274 return le_to_h_u32(buffer);
275 else
276 return be_to_h_u32(buffer);
279 /* read a uint16_t from a buffer in target memory endianness */
280 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
282 if (target->endianness == TARGET_LITTLE_ENDIAN)
283 return le_to_h_u16(buffer);
284 else
285 return be_to_h_u16(buffer);
288 /* read a uint8_t from a buffer in target memory endianness */
289 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
291 return *buffer & 0x0ff;
294 /* write a uint32_t to a buffer in target memory endianness */
295 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
297 if (target->endianness == TARGET_LITTLE_ENDIAN)
298 h_u32_to_le(buffer, value);
299 else
300 h_u32_to_be(buffer, value);
303 /* write a uint16_t to a buffer in target memory endianness */
304 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
306 if (target->endianness == TARGET_LITTLE_ENDIAN)
307 h_u16_to_le(buffer, value);
308 else
309 h_u16_to_be(buffer, value);
312 /* write a uint8_t to a buffer in target memory endianness */
313 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
315 *buffer = value;
318 /* return a pointer to a configured target; id is name or number */
319 struct target *get_target(const char *id)
321 struct target *target;
323 /* try as tcltarget name */
324 for (target = all_targets; target; target = target->next) {
325 if (target->cmd_name == NULL)
326 continue;
327 if (strcmp(id, target->cmd_name) == 0)
328 return target;
331 /* It's OK to remove this fallback sometime after August 2010 or so */
333 /* no match, try as number */
334 unsigned num;
335 if (parse_uint(id, &num) != ERROR_OK)
336 return NULL;
338 for (target = all_targets; target; target = target->next) {
339 if (target->target_number == (int)num) {
340 LOG_WARNING("use '%s' as target identifier, not '%u'",
341 target->cmd_name, num);
342 return target;
346 return NULL;
349 /* returns a pointer to the n-th configured target */
350 static struct target *get_target_by_num(int num)
352 struct target *target = all_targets;
354 while (target) {
355 if (target->target_number == num) {
356 return target;
358 target = target->next;
361 return NULL;
364 struct target* get_current_target(struct command_context *cmd_ctx)
366 struct target *target = get_target_by_num(cmd_ctx->current_target);
368 if (target == NULL)
370 LOG_ERROR("BUG: current_target out of bounds");
371 exit(-1);
374 return target;
377 int target_poll(struct target *target)
379 int retval;
381 /* We can't poll until after examine */
382 if (!target_was_examined(target))
384 /* Fail silently lest we pollute the log */
385 return ERROR_FAIL;
388 retval = target->type->poll(target);
389 if (retval != ERROR_OK)
390 return retval;
392 if (target->halt_issued)
394 if (target->state == TARGET_HALTED)
396 target->halt_issued = false;
397 } else
399 long long t = timeval_ms() - target->halt_issued_time;
400 if (t>1000)
402 target->halt_issued = false;
403 LOG_INFO("Halt timed out, wake up GDB.");
404 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
409 return ERROR_OK;
412 int target_halt(struct target *target)
414 int retval;
415 /* We can't poll until after examine */
416 if (!target_was_examined(target))
418 LOG_ERROR("Target not examined yet");
419 return ERROR_FAIL;
422 retval = target->type->halt(target);
423 if (retval != ERROR_OK)
424 return retval;
426 target->halt_issued = true;
427 target->halt_issued_time = timeval_ms();
429 return ERROR_OK;
433 * Make the target (re)start executing using its saved execution
434 * context (possibly with some modifications).
436 * @param target Which target should start executing.
437 * @param current True to use the target's saved program counter instead
438 * of the address parameter
439 * @param address Optionally used as the program counter.
440 * @param handle_breakpoints True iff breakpoints at the resumption PC
441 * should be skipped. (For example, maybe execution was stopped by
442 * such a breakpoint, in which case it would be counterprodutive to
443 * let it re-trigger.
444 * @param debug_execution False if all working areas allocated by OpenOCD
445 * should be released and/or restored to their original contents.
446 * (This would for example be true to run some downloaded "helper"
447 * algorithm code, which resides in one such working buffer and uses
448 * another for data storage.)
450 * @todo Resolve the ambiguity about what the "debug_execution" flag
451 * signifies. For example, Target implementations don't agree on how
452 * it relates to invalidation of the register cache, or to whether
453 * breakpoints and watchpoints should be enabled. (It would seem wrong
454 * to enable breakpoints when running downloaded "helper" algorithms
455 * (debug_execution true), since the breakpoints would be set to match
456 * target firmware being debugged, not the helper algorithm.... and
457 * enabling them could cause such helpers to malfunction (for example,
458 * by overwriting data with a breakpoint instruction. On the other
459 * hand the infrastructure for running such helpers might use this
460 * procedure but rely on hardware breakpoint to detect termination.)
462 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
464 int retval;
466 /* We can't poll until after examine */
467 if (!target_was_examined(target))
469 LOG_ERROR("Target not examined yet");
470 return ERROR_FAIL;
473 /* note that resume *must* be asynchronous. The CPU can halt before
474 * we poll. The CPU can even halt at the current PC as a result of
475 * a software breakpoint being inserted by (a bug?) the application.
477 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
478 return retval;
480 return retval;
483 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
485 char buf[100];
486 int retval;
487 Jim_Nvp *n;
488 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
489 if (n->name == NULL) {
490 LOG_ERROR("invalid reset mode");
491 return ERROR_FAIL;
494 /* disable polling during reset to make reset event scripts
495 * more predictable, i.e. dr/irscan & pathmove in events will
496 * not have JTAG operations injected into the middle of a sequence.
498 bool save_poll = jtag_poll_get_enabled();
500 jtag_poll_set_enabled(false);
502 sprintf(buf, "ocd_process_reset %s", n->name);
503 retval = Jim_Eval(cmd_ctx->interp, buf);
505 jtag_poll_set_enabled(save_poll);
507 if (retval != JIM_OK) {
508 Jim_PrintErrorMessage(cmd_ctx->interp);
509 return ERROR_FAIL;
512 /* We want any events to be processed before the prompt */
513 retval = target_call_timer_callbacks_now();
515 struct target *target;
516 for (target = all_targets; target; target = target->next) {
517 target->type->check_reset(target);
520 return retval;
523 static int identity_virt2phys(struct target *target,
524 uint32_t virtual, uint32_t *physical)
526 *physical = virtual;
527 return ERROR_OK;
530 static int no_mmu(struct target *target, int *enabled)
532 *enabled = 0;
533 return ERROR_OK;
536 static int default_examine(struct target *target)
538 target_set_examined(target);
539 return ERROR_OK;
542 /* no check by default */
543 static int default_check_reset(struct target *target)
545 return ERROR_OK;
548 int target_examine_one(struct target *target)
550 return target->type->examine(target);
553 static int jtag_enable_callback(enum jtag_event event, void *priv)
555 struct target *target = priv;
557 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
558 return ERROR_OK;
560 jtag_unregister_event_callback(jtag_enable_callback, target);
561 return target_examine_one(target);
565 /* Targets that correctly implement init + examine, i.e.
566 * no communication with target during init:
568 * XScale
570 int target_examine(void)
572 int retval = ERROR_OK;
573 struct target *target;
575 for (target = all_targets; target; target = target->next)
577 /* defer examination, but don't skip it */
578 if (!target->tap->enabled) {
579 jtag_register_event_callback(jtag_enable_callback,
580 target);
581 continue;
583 if ((retval = target_examine_one(target)) != ERROR_OK)
584 return retval;
586 return retval;
588 const char *target_type_name(struct target *target)
590 return target->type->name;
593 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
595 if (!target_was_examined(target))
597 LOG_ERROR("Target not examined yet");
598 return ERROR_FAIL;
600 return target->type->write_memory_imp(target, address, size, count, buffer);
603 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
605 if (!target_was_examined(target))
607 LOG_ERROR("Target not examined yet");
608 return ERROR_FAIL;
610 return target->type->read_memory_imp(target, address, size, count, buffer);
613 static int target_soft_reset_halt_imp(struct target *target)
615 if (!target_was_examined(target))
617 LOG_ERROR("Target not examined yet");
618 return ERROR_FAIL;
620 if (!target->type->soft_reset_halt_imp) {
621 LOG_ERROR("Target %s does not support soft_reset_halt",
622 target_name(target));
623 return ERROR_FAIL;
625 return target->type->soft_reset_halt_imp(target);
629 * Downloads a target-specific native code algorithm to the target,
630 * and executes it. * Note that some targets may need to set up, enable,
631 * and tear down a breakpoint (hard or * soft) to detect algorithm
632 * termination, while others may support lower overhead schemes where
633 * soft breakpoints embedded in the algorithm automatically terminate the
634 * algorithm.
636 * @param target used to run the algorithm
637 * @param arch_info target-specific description of the algorithm.
639 int target_run_algorithm(struct target *target,
640 int num_mem_params, struct mem_param *mem_params,
641 int num_reg_params, struct reg_param *reg_param,
642 uint32_t entry_point, uint32_t exit_point,
643 int timeout_ms, void *arch_info)
645 int retval = ERROR_FAIL;
647 if (!target_was_examined(target))
649 LOG_ERROR("Target not examined yet");
650 goto done;
652 if (!target->type->run_algorithm) {
653 LOG_ERROR("Target type '%s' does not support %s",
654 target_type_name(target), __func__);
655 goto done;
658 target->running_alg = true;
659 retval = target->type->run_algorithm(target,
660 num_mem_params, mem_params,
661 num_reg_params, reg_param,
662 entry_point, exit_point, timeout_ms, arch_info);
663 target->running_alg = false;
665 done:
666 return retval;
670 int target_read_memory(struct target *target,
671 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
673 return target->type->read_memory(target, address, size, count, buffer);
676 static int target_read_phys_memory(struct target *target,
677 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
679 return target->type->read_phys_memory(target, address, size, count, buffer);
682 int target_write_memory(struct target *target,
683 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
685 return target->type->write_memory(target, address, size, count, buffer);
688 static int target_write_phys_memory(struct target *target,
689 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
691 return target->type->write_phys_memory(target, address, size, count, buffer);
694 int target_bulk_write_memory(struct target *target,
695 uint32_t address, uint32_t count, uint8_t *buffer)
697 return target->type->bulk_write_memory(target, address, count, buffer);
700 int target_add_breakpoint(struct target *target,
701 struct breakpoint *breakpoint)
703 if (target->state != TARGET_HALTED) {
704 LOG_WARNING("target %s is not halted", target->cmd_name);
705 return ERROR_TARGET_NOT_HALTED;
707 return target->type->add_breakpoint(target, breakpoint);
709 int target_remove_breakpoint(struct target *target,
710 struct breakpoint *breakpoint)
712 return target->type->remove_breakpoint(target, breakpoint);
715 int target_add_watchpoint(struct target *target,
716 struct watchpoint *watchpoint)
718 if (target->state != TARGET_HALTED) {
719 LOG_WARNING("target %s is not halted", target->cmd_name);
720 return ERROR_TARGET_NOT_HALTED;
722 return target->type->add_watchpoint(target, watchpoint);
724 int target_remove_watchpoint(struct target *target,
725 struct watchpoint *watchpoint)
727 return target->type->remove_watchpoint(target, watchpoint);
730 int target_get_gdb_reg_list(struct target *target,
731 struct reg **reg_list[], int *reg_list_size)
733 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
735 int target_step(struct target *target,
736 int current, uint32_t address, int handle_breakpoints)
738 return target->type->step(target, current, address, handle_breakpoints);
743 * Reset the @c examined flag for the given target.
744 * Pure paranoia -- targets are zeroed on allocation.
746 static void target_reset_examined(struct target *target)
748 target->examined = false;
751 static int
752 err_read_phys_memory(struct target *target, uint32_t address,
753 uint32_t size, uint32_t count, uint8_t *buffer)
755 LOG_ERROR("Not implemented: %s", __func__);
756 return ERROR_FAIL;
759 static int
760 err_write_phys_memory(struct target *target, uint32_t address,
761 uint32_t size, uint32_t count, uint8_t *buffer)
763 LOG_ERROR("Not implemented: %s", __func__);
764 return ERROR_FAIL;
767 static int handle_target(void *priv);
769 static int target_init_one(struct command_context *cmd_ctx,
770 struct target *target)
772 target_reset_examined(target);
774 struct target_type *type = target->type;
775 if (type->examine == NULL)
776 type->examine = default_examine;
778 if (type->check_reset== NULL)
779 type->check_reset = default_check_reset;
781 int retval = type->init_target(cmd_ctx, target);
782 if (ERROR_OK != retval)
784 LOG_ERROR("target '%s' init failed", target_name(target));
785 return retval;
789 * @todo get rid of those *memory_imp() methods, now that all
790 * callers are using target_*_memory() accessors ... and make
791 * sure the "physical" paths handle the same issues.
793 /* a non-invasive way(in terms of patches) to add some code that
794 * runs before the type->write/read_memory implementation
796 type->write_memory_imp = target->type->write_memory;
797 type->write_memory = target_write_memory_imp;
799 type->read_memory_imp = target->type->read_memory;
800 type->read_memory = target_read_memory_imp;
802 type->soft_reset_halt_imp = target->type->soft_reset_halt;
803 type->soft_reset_halt = target_soft_reset_halt_imp;
805 /* Sanity-check MMU support ... stub in what we must, to help
806 * implement it in stages, but warn if we need to do so.
808 if (type->mmu)
810 if (type->write_phys_memory == NULL)
812 LOG_ERROR("type '%s' is missing write_phys_memory",
813 type->name);
814 type->write_phys_memory = err_write_phys_memory;
816 if (type->read_phys_memory == NULL)
818 LOG_ERROR("type '%s' is missing read_phys_memory",
819 type->name);
820 type->read_phys_memory = err_read_phys_memory;
822 if (type->virt2phys == NULL)
824 LOG_ERROR("type '%s' is missing virt2phys", type->name);
825 type->virt2phys = identity_virt2phys;
828 else
830 /* Make sure no-MMU targets all behave the same: make no
831 * distinction between physical and virtual addresses, and
832 * ensure that virt2phys() is always an identity mapping.
834 if (type->write_phys_memory || type->read_phys_memory
835 || type->virt2phys)
837 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
840 type->mmu = no_mmu;
841 type->write_phys_memory = type->write_memory;
842 type->read_phys_memory = type->read_memory;
843 type->virt2phys = identity_virt2phys;
845 return ERROR_OK;
848 static int target_init(struct command_context *cmd_ctx)
850 struct target *target;
851 int retval;
853 for (target = all_targets; target; target = target->next)
855 retval = target_init_one(cmd_ctx, target);
856 if (ERROR_OK != retval)
857 return retval;
860 if (!all_targets)
861 return ERROR_OK;
863 retval = target_register_user_commands(cmd_ctx);
864 if (ERROR_OK != retval)
865 return retval;
867 retval = target_register_timer_callback(&handle_target,
868 polling_interval, 1, cmd_ctx->interp);
869 if (ERROR_OK != retval)
870 return retval;
872 return ERROR_OK;
875 COMMAND_HANDLER(handle_target_init_command)
877 if (CMD_ARGC != 0)
878 return ERROR_COMMAND_SYNTAX_ERROR;
880 static bool target_initialized = false;
881 if (target_initialized)
883 LOG_INFO("'target init' has already been called");
884 return ERROR_OK;
886 target_initialized = true;
888 LOG_DEBUG("Initializing targets...");
889 return target_init(CMD_CTX);
892 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
894 struct target_event_callback **callbacks_p = &target_event_callbacks;
896 if (callback == NULL)
898 return ERROR_INVALID_ARGUMENTS;
901 if (*callbacks_p)
903 while ((*callbacks_p)->next)
904 callbacks_p = &((*callbacks_p)->next);
905 callbacks_p = &((*callbacks_p)->next);
908 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
909 (*callbacks_p)->callback = callback;
910 (*callbacks_p)->priv = priv;
911 (*callbacks_p)->next = NULL;
913 return ERROR_OK;
916 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
918 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
919 struct timeval now;
921 if (callback == NULL)
923 return ERROR_INVALID_ARGUMENTS;
926 if (*callbacks_p)
928 while ((*callbacks_p)->next)
929 callbacks_p = &((*callbacks_p)->next);
930 callbacks_p = &((*callbacks_p)->next);
933 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
934 (*callbacks_p)->callback = callback;
935 (*callbacks_p)->periodic = periodic;
936 (*callbacks_p)->time_ms = time_ms;
938 gettimeofday(&now, NULL);
939 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
940 time_ms -= (time_ms % 1000);
941 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
942 if ((*callbacks_p)->when.tv_usec > 1000000)
944 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
945 (*callbacks_p)->when.tv_sec += 1;
948 (*callbacks_p)->priv = priv;
949 (*callbacks_p)->next = NULL;
951 return ERROR_OK;
954 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
956 struct target_event_callback **p = &target_event_callbacks;
957 struct target_event_callback *c = target_event_callbacks;
959 if (callback == NULL)
961 return ERROR_INVALID_ARGUMENTS;
964 while (c)
966 struct target_event_callback *next = c->next;
967 if ((c->callback == callback) && (c->priv == priv))
969 *p = next;
970 free(c);
971 return ERROR_OK;
973 else
974 p = &(c->next);
975 c = next;
978 return ERROR_OK;
981 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
983 struct target_timer_callback **p = &target_timer_callbacks;
984 struct target_timer_callback *c = target_timer_callbacks;
986 if (callback == NULL)
988 return ERROR_INVALID_ARGUMENTS;
991 while (c)
993 struct target_timer_callback *next = c->next;
994 if ((c->callback == callback) && (c->priv == priv))
996 *p = next;
997 free(c);
998 return ERROR_OK;
1000 else
1001 p = &(c->next);
1002 c = next;
1005 return ERROR_OK;
1008 int target_call_event_callbacks(struct target *target, enum target_event event)
1010 struct target_event_callback *callback = target_event_callbacks;
1011 struct target_event_callback *next_callback;
1013 if (event == TARGET_EVENT_HALTED)
1015 /* execute early halted first */
1016 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1019 LOG_DEBUG("target event %i (%s)",
1020 event,
1021 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1023 target_handle_event(target, event);
1025 while (callback)
1027 next_callback = callback->next;
1028 callback->callback(target, event, callback->priv);
1029 callback = next_callback;
1032 return ERROR_OK;
1035 static int target_timer_callback_periodic_restart(
1036 struct target_timer_callback *cb, struct timeval *now)
1038 int time_ms = cb->time_ms;
1039 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1040 time_ms -= (time_ms % 1000);
1041 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1042 if (cb->when.tv_usec > 1000000)
1044 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1045 cb->when.tv_sec += 1;
1047 return ERROR_OK;
1050 static int target_call_timer_callback(struct target_timer_callback *cb,
1051 struct timeval *now)
1053 cb->callback(cb->priv);
1055 if (cb->periodic)
1056 return target_timer_callback_periodic_restart(cb, now);
1058 return target_unregister_timer_callback(cb->callback, cb->priv);
1061 static int target_call_timer_callbacks_check_time(int checktime)
1063 keep_alive();
1065 struct timeval now;
1066 gettimeofday(&now, NULL);
1068 struct target_timer_callback *callback = target_timer_callbacks;
1069 while (callback)
1071 // cleaning up may unregister and free this callback
1072 struct target_timer_callback *next_callback = callback->next;
1074 bool call_it = callback->callback &&
1075 ((!checktime && callback->periodic) ||
1076 now.tv_sec > callback->when.tv_sec ||
1077 (now.tv_sec == callback->when.tv_sec &&
1078 now.tv_usec >= callback->when.tv_usec));
1080 if (call_it)
1082 int retval = target_call_timer_callback(callback, &now);
1083 if (retval != ERROR_OK)
1084 return retval;
1087 callback = next_callback;
1090 return ERROR_OK;
1093 int target_call_timer_callbacks(void)
1095 return target_call_timer_callbacks_check_time(1);
1098 /* invoke periodic callbacks immediately */
1099 int target_call_timer_callbacks_now(void)
1101 return target_call_timer_callbacks_check_time(0);
1104 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1106 struct working_area *c = target->working_areas;
1107 struct working_area *new_wa = NULL;
1109 /* Reevaluate working area address based on MMU state*/
1110 if (target->working_areas == NULL)
1112 int retval;
1113 int enabled;
1115 retval = target->type->mmu(target, &enabled);
1116 if (retval != ERROR_OK)
1118 return retval;
1121 if (!enabled) {
1122 if (target->working_area_phys_spec) {
1123 LOG_DEBUG("MMU disabled, using physical "
1124 "address for working memory 0x%08x",
1125 (unsigned)target->working_area_phys);
1126 target->working_area = target->working_area_phys;
1127 } else {
1128 LOG_ERROR("No working memory available. "
1129 "Specify -work-area-phys to target.");
1130 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1132 } else {
1133 if (target->working_area_virt_spec) {
1134 LOG_DEBUG("MMU enabled, using virtual "
1135 "address for working memory 0x%08x",
1136 (unsigned)target->working_area_virt);
1137 target->working_area = target->working_area_virt;
1138 } else {
1139 LOG_ERROR("No working memory available. "
1140 "Specify -work-area-virt to target.");
1141 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1146 /* only allocate multiples of 4 byte */
1147 if (size % 4)
1149 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1150 size = (size + 3) & (~3);
1153 /* see if there's already a matching working area */
1154 while (c)
1156 if ((c->free) && (c->size == size))
1158 new_wa = c;
1159 break;
1161 c = c->next;
1164 /* if not, allocate a new one */
1165 if (!new_wa)
1167 struct working_area **p = &target->working_areas;
1168 uint32_t first_free = target->working_area;
1169 uint32_t free_size = target->working_area_size;
1171 c = target->working_areas;
1172 while (c)
1174 first_free += c->size;
1175 free_size -= c->size;
1176 p = &c->next;
1177 c = c->next;
1180 if (free_size < size)
1182 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1185 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1187 new_wa = malloc(sizeof(struct working_area));
1188 new_wa->next = NULL;
1189 new_wa->size = size;
1190 new_wa->address = first_free;
1192 if (target->backup_working_area)
1194 int retval;
1195 new_wa->backup = malloc(new_wa->size);
1196 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1198 free(new_wa->backup);
1199 free(new_wa);
1200 return retval;
1203 else
1205 new_wa->backup = NULL;
1208 /* put new entry in list */
1209 *p = new_wa;
1212 /* mark as used, and return the new (reused) area */
1213 new_wa->free = 0;
1214 *area = new_wa;
1216 /* user pointer */
1217 new_wa->user = area;
1219 return ERROR_OK;
1222 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1224 int retval;
1226 retval = target_alloc_working_area_try(target, size, area);
1227 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1229 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1231 return retval;
1235 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1237 if (area->free)
1238 return ERROR_OK;
1240 if (restore && target->backup_working_area)
1242 int retval;
1243 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1244 return retval;
1247 area->free = 1;
1249 /* mark user pointer invalid */
1250 *area->user = NULL;
1251 area->user = NULL;
1253 return ERROR_OK;
1256 int target_free_working_area(struct target *target, struct working_area *area)
1258 return target_free_working_area_restore(target, area, 1);
1261 /* free resources and restore memory, if restoring memory fails,
1262 * free up resources anyway
1264 static void target_free_all_working_areas_restore(struct target *target, int restore)
1266 struct working_area *c = target->working_areas;
1268 while (c)
1270 struct working_area *next = c->next;
1271 target_free_working_area_restore(target, c, restore);
1273 if (c->backup)
1274 free(c->backup);
1276 free(c);
1278 c = next;
1281 target->working_areas = NULL;
1284 void target_free_all_working_areas(struct target *target)
1286 target_free_all_working_areas_restore(target, 1);
1289 int target_arch_state(struct target *target)
1291 int retval;
1292 if (target == NULL)
1294 LOG_USER("No target has been configured");
1295 return ERROR_OK;
1298 LOG_USER("target state: %s", target_state_name( target ));
1300 if (target->state != TARGET_HALTED)
1301 return ERROR_OK;
1303 retval = target->type->arch_state(target);
1304 return retval;
1307 /* Single aligned words are guaranteed to use 16 or 32 bit access
1308 * mode respectively, otherwise data is handled as quickly as
1309 * possible
1311 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1313 int retval;
1314 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1315 (int)size, (unsigned)address);
1317 if (!target_was_examined(target))
1319 LOG_ERROR("Target not examined yet");
1320 return ERROR_FAIL;
1323 if (size == 0) {
1324 return ERROR_OK;
1327 if ((address + size - 1) < address)
1329 /* GDB can request this when e.g. PC is 0xfffffffc*/
1330 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1331 (unsigned)address,
1332 (unsigned)size);
1333 return ERROR_FAIL;
1336 if (((address % 2) == 0) && (size == 2))
1338 return target_write_memory(target, address, 2, 1, buffer);
1341 /* handle unaligned head bytes */
1342 if (address % 4)
1344 uint32_t unaligned = 4 - (address % 4);
1346 if (unaligned > size)
1347 unaligned = size;
1349 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1350 return retval;
1352 buffer += unaligned;
1353 address += unaligned;
1354 size -= unaligned;
1357 /* handle aligned words */
1358 if (size >= 4)
1360 int aligned = size - (size % 4);
1362 /* use bulk writes above a certain limit. This may have to be changed */
1363 if (aligned > 128)
1365 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1366 return retval;
1368 else
1370 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1371 return retval;
1374 buffer += aligned;
1375 address += aligned;
1376 size -= aligned;
1379 /* handle tail writes of less than 4 bytes */
1380 if (size > 0)
1382 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1383 return retval;
1386 return ERROR_OK;
1389 /* Single aligned words are guaranteed to use 16 or 32 bit access
1390 * mode respectively, otherwise data is handled as quickly as
1391 * possible
1393 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1395 int retval;
1396 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1397 (int)size, (unsigned)address);
1399 if (!target_was_examined(target))
1401 LOG_ERROR("Target not examined yet");
1402 return ERROR_FAIL;
1405 if (size == 0) {
1406 return ERROR_OK;
1409 if ((address + size - 1) < address)
1411 /* GDB can request this when e.g. PC is 0xfffffffc*/
1412 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1413 address,
1414 size);
1415 return ERROR_FAIL;
1418 if (((address % 2) == 0) && (size == 2))
1420 return target_read_memory(target, address, 2, 1, buffer);
1423 /* handle unaligned head bytes */
1424 if (address % 4)
1426 uint32_t unaligned = 4 - (address % 4);
1428 if (unaligned > size)
1429 unaligned = size;
1431 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1432 return retval;
1434 buffer += unaligned;
1435 address += unaligned;
1436 size -= unaligned;
1439 /* handle aligned words */
1440 if (size >= 4)
1442 int aligned = size - (size % 4);
1444 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1445 return retval;
1447 buffer += aligned;
1448 address += aligned;
1449 size -= aligned;
1452 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1453 if(size >=2)
1455 int aligned = size - (size%2);
1456 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1457 if (retval != ERROR_OK)
1458 return retval;
1460 buffer += aligned;
1461 address += aligned;
1462 size -= aligned;
1464 /* handle tail writes of less than 4 bytes */
1465 if (size > 0)
1467 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1468 return retval;
1471 return ERROR_OK;
1474 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1476 uint8_t *buffer;
1477 int retval;
1478 uint32_t i;
1479 uint32_t checksum = 0;
1480 if (!target_was_examined(target))
1482 LOG_ERROR("Target not examined yet");
1483 return ERROR_FAIL;
1486 if ((retval = target->type->checksum_memory(target, address,
1487 size, &checksum)) != ERROR_OK)
1489 buffer = malloc(size);
1490 if (buffer == NULL)
1492 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1493 return ERROR_INVALID_ARGUMENTS;
1495 retval = target_read_buffer(target, address, size, buffer);
1496 if (retval != ERROR_OK)
1498 free(buffer);
1499 return retval;
1502 /* convert to target endianess */
1503 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1505 uint32_t target_data;
1506 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1507 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1510 retval = image_calculate_checksum(buffer, size, &checksum);
1511 free(buffer);
1514 *crc = checksum;
1516 return retval;
1519 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1521 int retval;
1522 if (!target_was_examined(target))
1524 LOG_ERROR("Target not examined yet");
1525 return ERROR_FAIL;
1528 if (target->type->blank_check_memory == 0)
1529 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1531 retval = target->type->blank_check_memory(target, address, size, blank);
1533 return retval;
1536 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1538 uint8_t value_buf[4];
1539 if (!target_was_examined(target))
1541 LOG_ERROR("Target not examined yet");
1542 return ERROR_FAIL;
1545 int retval = target_read_memory(target, address, 4, 1, value_buf);
1547 if (retval == ERROR_OK)
1549 *value = target_buffer_get_u32(target, value_buf);
1550 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1551 address,
1552 *value);
1554 else
1556 *value = 0x0;
1557 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1558 address);
1561 return retval;
1564 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1566 uint8_t value_buf[2];
1567 if (!target_was_examined(target))
1569 LOG_ERROR("Target not examined yet");
1570 return ERROR_FAIL;
1573 int retval = target_read_memory(target, address, 2, 1, value_buf);
1575 if (retval == ERROR_OK)
1577 *value = target_buffer_get_u16(target, value_buf);
1578 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1579 address,
1580 *value);
1582 else
1584 *value = 0x0;
1585 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1586 address);
1589 return retval;
1592 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1594 int retval = target_read_memory(target, address, 1, 1, value);
1595 if (!target_was_examined(target))
1597 LOG_ERROR("Target not examined yet");
1598 return ERROR_FAIL;
1601 if (retval == ERROR_OK)
1603 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1604 address,
1605 *value);
1607 else
1609 *value = 0x0;
1610 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1611 address);
1614 return retval;
1617 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1619 int retval;
1620 uint8_t value_buf[4];
1621 if (!target_was_examined(target))
1623 LOG_ERROR("Target not examined yet");
1624 return ERROR_FAIL;
1627 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1628 address,
1629 value);
1631 target_buffer_set_u32(target, value_buf, value);
1632 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1634 LOG_DEBUG("failed: %i", retval);
1637 return retval;
1640 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1642 int retval;
1643 uint8_t value_buf[2];
1644 if (!target_was_examined(target))
1646 LOG_ERROR("Target not examined yet");
1647 return ERROR_FAIL;
1650 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1651 address,
1652 value);
1654 target_buffer_set_u16(target, value_buf, value);
1655 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1657 LOG_DEBUG("failed: %i", retval);
1660 return retval;
1663 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1665 int retval;
1666 if (!target_was_examined(target))
1668 LOG_ERROR("Target not examined yet");
1669 return ERROR_FAIL;
1672 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1673 address, value);
1675 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1677 LOG_DEBUG("failed: %i", retval);
1680 return retval;
1683 COMMAND_HANDLER(handle_targets_command)
1685 struct target *target = all_targets;
1687 if (CMD_ARGC == 1)
1689 target = get_target(CMD_ARGV[0]);
1690 if (target == NULL) {
1691 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1692 goto DumpTargets;
1694 if (!target->tap->enabled) {
1695 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1696 "can't be the current target\n",
1697 target->tap->dotted_name);
1698 return ERROR_FAIL;
1701 CMD_CTX->current_target = target->target_number;
1702 return ERROR_OK;
1704 DumpTargets:
1706 target = all_targets;
1707 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1708 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1709 while (target)
1711 const char *state;
1712 char marker = ' ';
1714 if (target->tap->enabled)
1715 state = target_state_name( target );
1716 else
1717 state = "tap-disabled";
1719 if (CMD_CTX->current_target == target->target_number)
1720 marker = '*';
1722 /* keep columns lined up to match the headers above */
1723 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1724 target->target_number,
1725 marker,
1726 target_name(target),
1727 target_type_name(target),
1728 Jim_Nvp_value2name_simple(nvp_target_endian,
1729 target->endianness)->name,
1730 target->tap->dotted_name,
1731 state);
1732 target = target->next;
1735 return ERROR_OK;
1738 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1740 static int powerDropout;
1741 static int srstAsserted;
1743 static int runPowerRestore;
1744 static int runPowerDropout;
1745 static int runSrstAsserted;
1746 static int runSrstDeasserted;
1748 static int sense_handler(void)
1750 static int prevSrstAsserted = 0;
1751 static int prevPowerdropout = 0;
1753 int retval;
1754 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1755 return retval;
1757 int powerRestored;
1758 powerRestored = prevPowerdropout && !powerDropout;
1759 if (powerRestored)
1761 runPowerRestore = 1;
1764 long long current = timeval_ms();
1765 static long long lastPower = 0;
1766 int waitMore = lastPower + 2000 > current;
1767 if (powerDropout && !waitMore)
1769 runPowerDropout = 1;
1770 lastPower = current;
1773 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1774 return retval;
1776 int srstDeasserted;
1777 srstDeasserted = prevSrstAsserted && !srstAsserted;
1779 static long long lastSrst = 0;
1780 waitMore = lastSrst + 2000 > current;
1781 if (srstDeasserted && !waitMore)
1783 runSrstDeasserted = 1;
1784 lastSrst = current;
1787 if (!prevSrstAsserted && srstAsserted)
1789 runSrstAsserted = 1;
1792 prevSrstAsserted = srstAsserted;
1793 prevPowerdropout = powerDropout;
1795 if (srstDeasserted || powerRestored)
1797 /* Other than logging the event we can't do anything here.
1798 * Issuing a reset is a particularly bad idea as we might
1799 * be inside a reset already.
1803 return ERROR_OK;
1806 static int backoff_times = 0;
1807 static int backoff_count = 0;
1809 /* process target state changes */
1810 static int handle_target(void *priv)
1812 Jim_Interp *interp = (Jim_Interp *)priv;
1813 int retval = ERROR_OK;
1815 if (!is_jtag_poll_safe())
1817 /* polling is disabled currently */
1818 return ERROR_OK;
1821 /* we do not want to recurse here... */
1822 static int recursive = 0;
1823 if (! recursive)
1825 recursive = 1;
1826 sense_handler();
1827 /* danger! running these procedures can trigger srst assertions and power dropouts.
1828 * We need to avoid an infinite loop/recursion here and we do that by
1829 * clearing the flags after running these events.
1831 int did_something = 0;
1832 if (runSrstAsserted)
1834 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1835 Jim_Eval(interp, "srst_asserted");
1836 did_something = 1;
1838 if (runSrstDeasserted)
1840 Jim_Eval(interp, "srst_deasserted");
1841 did_something = 1;
1843 if (runPowerDropout)
1845 LOG_INFO("Power dropout detected, running power_dropout proc.");
1846 Jim_Eval(interp, "power_dropout");
1847 did_something = 1;
1849 if (runPowerRestore)
1851 Jim_Eval(interp, "power_restore");
1852 did_something = 1;
1855 if (did_something)
1857 /* clear detect flags */
1858 sense_handler();
1861 /* clear action flags */
1863 runSrstAsserted = 0;
1864 runSrstDeasserted = 0;
1865 runPowerRestore = 0;
1866 runPowerDropout = 0;
1868 recursive = 0;
1871 if (backoff_times > backoff_count)
1873 /* do not poll this time as we failed previously */
1874 backoff_count++;
1875 return ERROR_OK;
1877 backoff_count = 0;
1879 /* Poll targets for state changes unless that's globally disabled.
1880 * Skip targets that are currently disabled.
1882 for (struct target *target = all_targets;
1883 is_jtag_poll_safe() && target;
1884 target = target->next)
1886 if (!target->tap->enabled)
1887 continue;
1889 /* only poll target if we've got power and srst isn't asserted */
1890 if (!powerDropout && !srstAsserted)
1892 /* polling may fail silently until the target has been examined */
1893 if ((retval = target_poll(target)) != ERROR_OK)
1895 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1896 if (backoff_times * polling_interval < 5000)
1898 backoff_times *= 2;
1899 backoff_times++;
1901 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1903 /* Tell GDB to halt the debugger. This allows the user to
1904 * run monitor commands to handle the situation.
1906 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1907 return retval;
1909 /* Since we succeeded, we reset backoff count */
1910 if (backoff_times > 0)
1912 LOG_USER("Polling succeeded again");
1914 backoff_times = 0;
1918 return retval;
1921 COMMAND_HANDLER(handle_reg_command)
1923 struct target *target;
1924 struct reg *reg = NULL;
1925 unsigned count = 0;
1926 char *value;
1928 LOG_DEBUG("-");
1930 target = get_current_target(CMD_CTX);
1932 /* list all available registers for the current target */
1933 if (CMD_ARGC == 0)
1935 struct reg_cache *cache = target->reg_cache;
1937 count = 0;
1938 while (cache)
1940 unsigned i;
1942 command_print(CMD_CTX, "===== %s", cache->name);
1944 for (i = 0, reg = cache->reg_list;
1945 i < cache->num_regs;
1946 i++, reg++, count++)
1948 /* only print cached values if they are valid */
1949 if (reg->valid) {
1950 value = buf_to_str(reg->value,
1951 reg->size, 16);
1952 command_print(CMD_CTX,
1953 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1954 count, reg->name,
1955 reg->size, value,
1956 reg->dirty
1957 ? " (dirty)"
1958 : "");
1959 free(value);
1960 } else {
1961 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1962 count, reg->name,
1963 reg->size) ;
1966 cache = cache->next;
1969 return ERROR_OK;
1972 /* access a single register by its ordinal number */
1973 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1975 unsigned num;
1976 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1978 struct reg_cache *cache = target->reg_cache;
1979 count = 0;
1980 while (cache)
1982 unsigned i;
1983 for (i = 0; i < cache->num_regs; i++)
1985 if (count++ == num)
1987 reg = &cache->reg_list[i];
1988 break;
1991 if (reg)
1992 break;
1993 cache = cache->next;
1996 if (!reg)
1998 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1999 return ERROR_OK;
2001 } else /* access a single register by its name */
2003 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2005 if (!reg)
2007 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2008 return ERROR_OK;
2012 /* display a register */
2013 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2015 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2016 reg->valid = 0;
2018 if (reg->valid == 0)
2020 reg->type->get(reg);
2022 value = buf_to_str(reg->value, reg->size, 16);
2023 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2024 free(value);
2025 return ERROR_OK;
2028 /* set register value */
2029 if (CMD_ARGC == 2)
2031 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2032 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2034 reg->type->set(reg, buf);
2036 value = buf_to_str(reg->value, reg->size, 16);
2037 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2038 free(value);
2040 free(buf);
2042 return ERROR_OK;
2045 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2047 return ERROR_OK;
2050 COMMAND_HANDLER(handle_poll_command)
2052 int retval = ERROR_OK;
2053 struct target *target = get_current_target(CMD_CTX);
2055 if (CMD_ARGC == 0)
2057 command_print(CMD_CTX, "background polling: %s",
2058 jtag_poll_get_enabled() ? "on" : "off");
2059 command_print(CMD_CTX, "TAP: %s (%s)",
2060 target->tap->dotted_name,
2061 target->tap->enabled ? "enabled" : "disabled");
2062 if (!target->tap->enabled)
2063 return ERROR_OK;
2064 if ((retval = target_poll(target)) != ERROR_OK)
2065 return retval;
2066 if ((retval = target_arch_state(target)) != ERROR_OK)
2067 return retval;
2069 else if (CMD_ARGC == 1)
2071 bool enable;
2072 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2073 jtag_poll_set_enabled(enable);
2075 else
2077 return ERROR_COMMAND_SYNTAX_ERROR;
2080 return retval;
2083 COMMAND_HANDLER(handle_wait_halt_command)
2085 if (CMD_ARGC > 1)
2086 return ERROR_COMMAND_SYNTAX_ERROR;
2088 unsigned ms = 5000;
2089 if (1 == CMD_ARGC)
2091 int retval = parse_uint(CMD_ARGV[0], &ms);
2092 if (ERROR_OK != retval)
2094 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2095 return ERROR_COMMAND_SYNTAX_ERROR;
2097 // convert seconds (given) to milliseconds (needed)
2098 ms *= 1000;
2101 struct target *target = get_current_target(CMD_CTX);
2102 return target_wait_state(target, TARGET_HALTED, ms);
2105 /* wait for target state to change. The trick here is to have a low
2106 * latency for short waits and not to suck up all the CPU time
2107 * on longer waits.
2109 * After 500ms, keep_alive() is invoked
2111 int target_wait_state(struct target *target, enum target_state state, int ms)
2113 int retval;
2114 long long then = 0, cur;
2115 int once = 1;
2117 for (;;)
2119 if ((retval = target_poll(target)) != ERROR_OK)
2120 return retval;
2121 if (target->state == state)
2123 break;
2125 cur = timeval_ms();
2126 if (once)
2128 once = 0;
2129 then = timeval_ms();
2130 LOG_DEBUG("waiting for target %s...",
2131 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2134 if (cur-then > 500)
2136 keep_alive();
2139 if ((cur-then) > ms)
2141 LOG_ERROR("timed out while waiting for target %s",
2142 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2143 return ERROR_FAIL;
2147 return ERROR_OK;
2150 COMMAND_HANDLER(handle_halt_command)
2152 LOG_DEBUG("-");
2154 struct target *target = get_current_target(CMD_CTX);
2155 int retval = target_halt(target);
2156 if (ERROR_OK != retval)
2157 return retval;
2159 if (CMD_ARGC == 1)
2161 unsigned wait_local;
2162 retval = parse_uint(CMD_ARGV[0], &wait_local);
2163 if (ERROR_OK != retval)
2164 return ERROR_COMMAND_SYNTAX_ERROR;
2165 if (!wait_local)
2166 return ERROR_OK;
2169 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2172 COMMAND_HANDLER(handle_soft_reset_halt_command)
2174 struct target *target = get_current_target(CMD_CTX);
2176 LOG_USER("requesting target halt and executing a soft reset");
2178 target->type->soft_reset_halt(target);
2180 return ERROR_OK;
2183 COMMAND_HANDLER(handle_reset_command)
2185 if (CMD_ARGC > 1)
2186 return ERROR_COMMAND_SYNTAX_ERROR;
2188 enum target_reset_mode reset_mode = RESET_RUN;
2189 if (CMD_ARGC == 1)
2191 const Jim_Nvp *n;
2192 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2193 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2194 return ERROR_COMMAND_SYNTAX_ERROR;
2196 reset_mode = n->value;
2199 /* reset *all* targets */
2200 return target_process_reset(CMD_CTX, reset_mode);
2204 COMMAND_HANDLER(handle_resume_command)
2206 int current = 1;
2207 if (CMD_ARGC > 1)
2208 return ERROR_COMMAND_SYNTAX_ERROR;
2210 struct target *target = get_current_target(CMD_CTX);
2211 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2213 /* with no CMD_ARGV, resume from current pc, addr = 0,
2214 * with one arguments, addr = CMD_ARGV[0],
2215 * handle breakpoints, not debugging */
2216 uint32_t addr = 0;
2217 if (CMD_ARGC == 1)
2219 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2220 current = 0;
2223 return target_resume(target, current, addr, 1, 0);
2226 COMMAND_HANDLER(handle_step_command)
2228 if (CMD_ARGC > 1)
2229 return ERROR_COMMAND_SYNTAX_ERROR;
2231 LOG_DEBUG("-");
2233 /* with no CMD_ARGV, step from current pc, addr = 0,
2234 * with one argument addr = CMD_ARGV[0],
2235 * handle breakpoints, debugging */
2236 uint32_t addr = 0;
2237 int current_pc = 1;
2238 if (CMD_ARGC == 1)
2240 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2241 current_pc = 0;
2244 struct target *target = get_current_target(CMD_CTX);
2246 return target->type->step(target, current_pc, addr, 1);
2249 static void handle_md_output(struct command_context *cmd_ctx,
2250 struct target *target, uint32_t address, unsigned size,
2251 unsigned count, const uint8_t *buffer)
2253 const unsigned line_bytecnt = 32;
2254 unsigned line_modulo = line_bytecnt / size;
2256 char output[line_bytecnt * 4 + 1];
2257 unsigned output_len = 0;
2259 const char *value_fmt;
2260 switch (size) {
2261 case 4: value_fmt = "%8.8x "; break;
2262 case 2: value_fmt = "%4.4x "; break;
2263 case 1: value_fmt = "%2.2x "; break;
2264 default:
2265 /* "can't happen", caller checked */
2266 LOG_ERROR("invalid memory read size: %u", size);
2267 return;
2270 for (unsigned i = 0; i < count; i++)
2272 if (i % line_modulo == 0)
2274 output_len += snprintf(output + output_len,
2275 sizeof(output) - output_len,
2276 "0x%8.8x: ",
2277 (unsigned)(address + (i*size)));
2280 uint32_t value = 0;
2281 const uint8_t *value_ptr = buffer + i * size;
2282 switch (size) {
2283 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2284 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2285 case 1: value = *value_ptr;
2287 output_len += snprintf(output + output_len,
2288 sizeof(output) - output_len,
2289 value_fmt, value);
2291 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2293 command_print(cmd_ctx, "%s", output);
2294 output_len = 0;
2299 COMMAND_HANDLER(handle_md_command)
2301 if (CMD_ARGC < 1)
2302 return ERROR_COMMAND_SYNTAX_ERROR;
2304 unsigned size = 0;
2305 switch (CMD_NAME[2]) {
2306 case 'w': size = 4; break;
2307 case 'h': size = 2; break;
2308 case 'b': size = 1; break;
2309 default: return ERROR_COMMAND_SYNTAX_ERROR;
2312 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2313 int (*fn)(struct target *target,
2314 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2315 if (physical)
2317 CMD_ARGC--;
2318 CMD_ARGV++;
2319 fn=target_read_phys_memory;
2320 } else
2322 fn=target_read_memory;
2324 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2326 return ERROR_COMMAND_SYNTAX_ERROR;
2329 uint32_t address;
2330 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2332 unsigned count = 1;
2333 if (CMD_ARGC == 2)
2334 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2336 uint8_t *buffer = calloc(count, size);
2338 struct target *target = get_current_target(CMD_CTX);
2339 int retval = fn(target, address, size, count, buffer);
2340 if (ERROR_OK == retval)
2341 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2343 free(buffer);
2345 return retval;
2348 typedef int (*target_write_fn)(struct target *target,
2349 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2351 static int target_write_memory_fast(struct target *target,
2352 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2354 return target_write_buffer(target, address, size * count, buffer);
2357 static int target_fill_mem(struct target *target,
2358 uint32_t address,
2359 target_write_fn fn,
2360 unsigned data_size,
2361 /* value */
2362 uint32_t b,
2363 /* count */
2364 unsigned c)
2366 /* We have to write in reasonably large chunks to be able
2367 * to fill large memory areas with any sane speed */
2368 const unsigned chunk_size = 16384;
2369 uint8_t *target_buf = malloc(chunk_size * data_size);
2370 if (target_buf == NULL)
2372 LOG_ERROR("Out of memory");
2373 return ERROR_FAIL;
2376 for (unsigned i = 0; i < chunk_size; i ++)
2378 switch (data_size)
2380 case 4:
2381 target_buffer_set_u32(target, target_buf + i*data_size, b);
2382 break;
2383 case 2:
2384 target_buffer_set_u16(target, target_buf + i*data_size, b);
2385 break;
2386 case 1:
2387 target_buffer_set_u8(target, target_buf + i*data_size, b);
2388 break;
2389 default:
2390 exit(-1);
2394 int retval = ERROR_OK;
2396 for (unsigned x = 0; x < c; x += chunk_size)
2398 unsigned current;
2399 current = c - x;
2400 if (current > chunk_size)
2402 current = chunk_size;
2404 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2405 if (retval != ERROR_OK)
2407 break;
2409 /* avoid GDB timeouts */
2410 keep_alive();
2412 free(target_buf);
2414 return retval;
2418 COMMAND_HANDLER(handle_mw_command)
2420 if (CMD_ARGC < 2)
2422 return ERROR_COMMAND_SYNTAX_ERROR;
2424 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2425 target_write_fn fn;
2426 if (physical)
2428 CMD_ARGC--;
2429 CMD_ARGV++;
2430 fn=target_write_phys_memory;
2431 } else
2433 fn = target_write_memory_fast;
2435 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2436 return ERROR_COMMAND_SYNTAX_ERROR;
2438 uint32_t address;
2439 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2441 uint32_t value;
2442 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2444 unsigned count = 1;
2445 if (CMD_ARGC == 3)
2446 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2448 struct target *target = get_current_target(CMD_CTX);
2449 unsigned wordsize;
2450 switch (CMD_NAME[2])
2452 case 'w':
2453 wordsize = 4;
2454 break;
2455 case 'h':
2456 wordsize = 2;
2457 break;
2458 case 'b':
2459 wordsize = 1;
2460 break;
2461 default:
2462 return ERROR_COMMAND_SYNTAX_ERROR;
2465 return target_fill_mem(target, address, fn, wordsize, value, count);
2468 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2469 uint32_t *min_address, uint32_t *max_address)
2471 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2472 return ERROR_COMMAND_SYNTAX_ERROR;
2474 /* a base address isn't always necessary,
2475 * default to 0x0 (i.e. don't relocate) */
2476 if (CMD_ARGC >= 2)
2478 uint32_t addr;
2479 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2480 image->base_address = addr;
2481 image->base_address_set = 1;
2483 else
2484 image->base_address_set = 0;
2486 image->start_address_set = 0;
2488 if (CMD_ARGC >= 4)
2490 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2492 if (CMD_ARGC == 5)
2494 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2495 // use size (given) to find max (required)
2496 *max_address += *min_address;
2499 if (*min_address > *max_address)
2500 return ERROR_COMMAND_SYNTAX_ERROR;
2502 return ERROR_OK;
2505 COMMAND_HANDLER(handle_load_image_command)
2507 uint8_t *buffer;
2508 size_t buf_cnt;
2509 uint32_t image_size;
2510 uint32_t min_address = 0;
2511 uint32_t max_address = 0xffffffff;
2512 int i;
2513 struct image image;
2515 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2516 &image, &min_address, &max_address);
2517 if (ERROR_OK != retval)
2518 return retval;
2520 struct target *target = get_current_target(CMD_CTX);
2522 struct duration bench;
2523 duration_start(&bench);
2525 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2527 return ERROR_OK;
2530 image_size = 0x0;
2531 retval = ERROR_OK;
2532 for (i = 0; i < image.num_sections; i++)
2534 buffer = malloc(image.sections[i].size);
2535 if (buffer == NULL)
2537 command_print(CMD_CTX,
2538 "error allocating buffer for section (%d bytes)",
2539 (int)(image.sections[i].size));
2540 break;
2543 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2545 free(buffer);
2546 break;
2549 uint32_t offset = 0;
2550 uint32_t length = buf_cnt;
2552 /* DANGER!!! beware of unsigned comparision here!!! */
2554 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2555 (image.sections[i].base_address < max_address))
2557 if (image.sections[i].base_address < min_address)
2559 /* clip addresses below */
2560 offset += min_address-image.sections[i].base_address;
2561 length -= offset;
2564 if (image.sections[i].base_address + buf_cnt > max_address)
2566 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2569 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2571 free(buffer);
2572 break;
2574 image_size += length;
2575 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2576 (unsigned int)length,
2577 image.sections[i].base_address + offset);
2580 free(buffer);
2583 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2585 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2586 "in %fs (%0.3f KiB/s)", image_size,
2587 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2590 image_close(&image);
2592 return retval;
2596 COMMAND_HANDLER(handle_dump_image_command)
2598 struct fileio fileio;
2600 uint8_t buffer[560];
2601 int retvaltemp;
2604 struct target *target = get_current_target(CMD_CTX);
2606 if (CMD_ARGC != 3)
2608 command_print(CMD_CTX, "usage: dump_image <filename> <address> <size>");
2609 return ERROR_OK;
2612 uint32_t address;
2613 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2614 uint32_t size;
2615 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2617 if (fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2619 return ERROR_OK;
2622 struct duration bench;
2623 duration_start(&bench);
2625 int retval = ERROR_OK;
2626 while (size > 0)
2628 size_t size_written;
2629 uint32_t this_run_size = (size > 560) ? 560 : size;
2630 retval = target_read_buffer(target, address, this_run_size, buffer);
2631 if (retval != ERROR_OK)
2633 break;
2636 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2637 if (retval != ERROR_OK)
2639 break;
2642 size -= this_run_size;
2643 address += this_run_size;
2646 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2648 int filesize;
2649 retval = fileio_size(&fileio, &filesize);
2650 if (retval != ERROR_OK)
2651 return retval;
2652 command_print(CMD_CTX,
2653 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2654 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2657 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2658 return retvaltemp;
2660 return retval;
2663 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2665 uint8_t *buffer;
2666 size_t buf_cnt;
2667 uint32_t image_size;
2668 int i;
2669 int retval;
2670 uint32_t checksum = 0;
2671 uint32_t mem_checksum = 0;
2673 struct image image;
2675 struct target *target = get_current_target(CMD_CTX);
2677 if (CMD_ARGC < 1)
2679 return ERROR_COMMAND_SYNTAX_ERROR;
2682 if (!target)
2684 LOG_ERROR("no target selected");
2685 return ERROR_FAIL;
2688 struct duration bench;
2689 duration_start(&bench);
2691 if (CMD_ARGC >= 2)
2693 uint32_t addr;
2694 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2695 image.base_address = addr;
2696 image.base_address_set = 1;
2698 else
2700 image.base_address_set = 0;
2701 image.base_address = 0x0;
2704 image.start_address_set = 0;
2706 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2708 return retval;
2711 image_size = 0x0;
2712 int diffs = 0;
2713 retval = ERROR_OK;
2714 for (i = 0; i < image.num_sections; i++)
2716 buffer = malloc(image.sections[i].size);
2717 if (buffer == NULL)
2719 command_print(CMD_CTX,
2720 "error allocating buffer for section (%d bytes)",
2721 (int)(image.sections[i].size));
2722 break;
2724 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2726 free(buffer);
2727 break;
2730 if (verify)
2732 /* calculate checksum of image */
2733 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2734 if (retval != ERROR_OK)
2736 free(buffer);
2737 break;
2740 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2741 if (retval != ERROR_OK)
2743 free(buffer);
2744 break;
2747 if (checksum != mem_checksum)
2749 /* failed crc checksum, fall back to a binary compare */
2750 uint8_t *data;
2752 if (diffs == 0)
2754 LOG_ERROR("checksum mismatch - attempting binary compare");
2757 data = (uint8_t*)malloc(buf_cnt);
2759 /* Can we use 32bit word accesses? */
2760 int size = 1;
2761 int count = buf_cnt;
2762 if ((count % 4) == 0)
2764 size *= 4;
2765 count /= 4;
2767 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2768 if (retval == ERROR_OK)
2770 uint32_t t;
2771 for (t = 0; t < buf_cnt; t++)
2773 if (data[t] != buffer[t])
2775 command_print(CMD_CTX,
2776 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2777 diffs,
2778 (unsigned)(t + image.sections[i].base_address),
2779 data[t],
2780 buffer[t]);
2781 if (diffs++ >= 127)
2783 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2784 free(data);
2785 free(buffer);
2786 goto done;
2789 keep_alive();
2792 free(data);
2794 } else
2796 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2797 image.sections[i].base_address,
2798 buf_cnt);
2801 free(buffer);
2802 image_size += buf_cnt;
2804 if (diffs > 0)
2806 command_print(CMD_CTX, "No more differences found.");
2808 done:
2809 if (diffs > 0)
2811 retval = ERROR_FAIL;
2813 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2815 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2816 "in %fs (%0.3f KiB/s)", image_size,
2817 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2820 image_close(&image);
2822 return retval;
2825 COMMAND_HANDLER(handle_verify_image_command)
2827 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2830 COMMAND_HANDLER(handle_test_image_command)
2832 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2835 static int handle_bp_command_list(struct command_context *cmd_ctx)
2837 struct target *target = get_current_target(cmd_ctx);
2838 struct breakpoint *breakpoint = target->breakpoints;
2839 while (breakpoint)
2841 if (breakpoint->type == BKPT_SOFT)
2843 char* buf = buf_to_str(breakpoint->orig_instr,
2844 breakpoint->length, 16);
2845 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2846 breakpoint->address,
2847 breakpoint->length,
2848 breakpoint->set, buf);
2849 free(buf);
2851 else
2853 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2854 breakpoint->address,
2855 breakpoint->length, breakpoint->set);
2858 breakpoint = breakpoint->next;
2860 return ERROR_OK;
2863 static int handle_bp_command_set(struct command_context *cmd_ctx,
2864 uint32_t addr, uint32_t length, int hw)
2866 struct target *target = get_current_target(cmd_ctx);
2867 int retval = breakpoint_add(target, addr, length, hw);
2868 if (ERROR_OK == retval)
2869 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2870 else
2871 LOG_ERROR("Failure setting breakpoint");
2872 return retval;
2875 COMMAND_HANDLER(handle_bp_command)
2877 if (CMD_ARGC == 0)
2878 return handle_bp_command_list(CMD_CTX);
2880 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2882 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2883 return ERROR_COMMAND_SYNTAX_ERROR;
2886 uint32_t addr;
2887 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2888 uint32_t length;
2889 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2891 int hw = BKPT_SOFT;
2892 if (CMD_ARGC == 3)
2894 if (strcmp(CMD_ARGV[2], "hw") == 0)
2895 hw = BKPT_HARD;
2896 else
2897 return ERROR_COMMAND_SYNTAX_ERROR;
2900 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2903 COMMAND_HANDLER(handle_rbp_command)
2905 if (CMD_ARGC != 1)
2906 return ERROR_COMMAND_SYNTAX_ERROR;
2908 uint32_t addr;
2909 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2911 struct target *target = get_current_target(CMD_CTX);
2912 breakpoint_remove(target, addr);
2914 return ERROR_OK;
2917 COMMAND_HANDLER(handle_wp_command)
2919 struct target *target = get_current_target(CMD_CTX);
2921 if (CMD_ARGC == 0)
2923 struct watchpoint *watchpoint = target->watchpoints;
2925 while (watchpoint)
2927 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2928 ", len: 0x%8.8" PRIx32
2929 ", r/w/a: %i, value: 0x%8.8" PRIx32
2930 ", mask: 0x%8.8" PRIx32,
2931 watchpoint->address,
2932 watchpoint->length,
2933 (int)watchpoint->rw,
2934 watchpoint->value,
2935 watchpoint->mask);
2936 watchpoint = watchpoint->next;
2938 return ERROR_OK;
2941 enum watchpoint_rw type = WPT_ACCESS;
2942 uint32_t addr = 0;
2943 uint32_t length = 0;
2944 uint32_t data_value = 0x0;
2945 uint32_t data_mask = 0xffffffff;
2947 switch (CMD_ARGC)
2949 case 5:
2950 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2951 // fall through
2952 case 4:
2953 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2954 // fall through
2955 case 3:
2956 switch (CMD_ARGV[2][0])
2958 case 'r':
2959 type = WPT_READ;
2960 break;
2961 case 'w':
2962 type = WPT_WRITE;
2963 break;
2964 case 'a':
2965 type = WPT_ACCESS;
2966 break;
2967 default:
2968 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2969 return ERROR_COMMAND_SYNTAX_ERROR;
2971 // fall through
2972 case 2:
2973 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2974 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2975 break;
2977 default:
2978 command_print(CMD_CTX, "usage: wp [address length "
2979 "[(r|w|a) [value [mask]]]]");
2980 return ERROR_COMMAND_SYNTAX_ERROR;
2983 int retval = watchpoint_add(target, addr, length, type,
2984 data_value, data_mask);
2985 if (ERROR_OK != retval)
2986 LOG_ERROR("Failure setting watchpoints");
2988 return retval;
2991 COMMAND_HANDLER(handle_rwp_command)
2993 if (CMD_ARGC != 1)
2994 return ERROR_COMMAND_SYNTAX_ERROR;
2996 uint32_t addr;
2997 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2999 struct target *target = get_current_target(CMD_CTX);
3000 watchpoint_remove(target, addr);
3002 return ERROR_OK;
3007 * Translate a virtual address to a physical address.
3009 * The low-level target implementation must have logged a detailed error
3010 * which is forwarded to telnet/GDB session.
3012 COMMAND_HANDLER(handle_virt2phys_command)
3014 if (CMD_ARGC != 1)
3015 return ERROR_COMMAND_SYNTAX_ERROR;
3017 uint32_t va;
3018 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3019 uint32_t pa;
3021 struct target *target = get_current_target(CMD_CTX);
3022 int retval = target->type->virt2phys(target, va, &pa);
3023 if (retval == ERROR_OK)
3024 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3026 return retval;
3029 static void writeData(FILE *f, const void *data, size_t len)
3031 size_t written = fwrite(data, 1, len, f);
3032 if (written != len)
3033 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3036 static void writeLong(FILE *f, int l)
3038 int i;
3039 for (i = 0; i < 4; i++)
3041 char c = (l >> (i*8))&0xff;
3042 writeData(f, &c, 1);
3047 static void writeString(FILE *f, char *s)
3049 writeData(f, s, strlen(s));
3052 /* Dump a gmon.out histogram file. */
3053 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3055 uint32_t i;
3056 FILE *f = fopen(filename, "w");
3057 if (f == NULL)
3058 return;
3059 writeString(f, "gmon");
3060 writeLong(f, 0x00000001); /* Version */
3061 writeLong(f, 0); /* padding */
3062 writeLong(f, 0); /* padding */
3063 writeLong(f, 0); /* padding */
3065 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3066 writeData(f, &zero, 1);
3068 /* figure out bucket size */
3069 uint32_t min = samples[0];
3070 uint32_t max = samples[0];
3071 for (i = 0; i < sampleNum; i++)
3073 if (min > samples[i])
3075 min = samples[i];
3077 if (max < samples[i])
3079 max = samples[i];
3083 int addressSpace = (max-min + 1);
3085 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
3086 uint32_t length = addressSpace;
3087 if (length > maxBuckets)
3089 length = maxBuckets;
3091 int *buckets = malloc(sizeof(int)*length);
3092 if (buckets == NULL)
3094 fclose(f);
3095 return;
3097 memset(buckets, 0, sizeof(int)*length);
3098 for (i = 0; i < sampleNum;i++)
3100 uint32_t address = samples[i];
3101 long long a = address-min;
3102 long long b = length-1;
3103 long long c = addressSpace-1;
3104 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3105 buckets[index_t]++;
3108 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3109 writeLong(f, min); /* low_pc */
3110 writeLong(f, max); /* high_pc */
3111 writeLong(f, length); /* # of samples */
3112 writeLong(f, 64000000); /* 64MHz */
3113 writeString(f, "seconds");
3114 for (i = 0; i < (15-strlen("seconds")); i++)
3115 writeData(f, &zero, 1);
3116 writeString(f, "s");
3118 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3120 char *data = malloc(2*length);
3121 if (data != NULL)
3123 for (i = 0; i < length;i++)
3125 int val;
3126 val = buckets[i];
3127 if (val > 65535)
3129 val = 65535;
3131 data[i*2]=val&0xff;
3132 data[i*2 + 1]=(val >> 8)&0xff;
3134 free(buckets);
3135 writeData(f, data, length * 2);
3136 free(data);
3137 } else
3139 free(buckets);
3142 fclose(f);
3145 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3146 * which will be used as a random sampling of PC */
3147 COMMAND_HANDLER(handle_profile_command)
3149 struct target *target = get_current_target(CMD_CTX);
3150 struct timeval timeout, now;
3152 gettimeofday(&timeout, NULL);
3153 if (CMD_ARGC != 2)
3155 return ERROR_COMMAND_SYNTAX_ERROR;
3157 unsigned offset;
3158 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3160 timeval_add_time(&timeout, offset, 0);
3163 * @todo: Some cores let us sample the PC without the
3164 * annoying halt/resume step; for example, ARMv7 PCSR.
3165 * Provide a way to use that more efficient mechanism.
3168 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3170 static const int maxSample = 10000;
3171 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3172 if (samples == NULL)
3173 return ERROR_OK;
3175 int numSamples = 0;
3176 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3177 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3179 for (;;)
3181 int retval;
3182 target_poll(target);
3183 if (target->state == TARGET_HALTED)
3185 uint32_t t=*((uint32_t *)reg->value);
3186 samples[numSamples++]=t;
3187 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3188 target_poll(target);
3189 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3190 } else if (target->state == TARGET_RUNNING)
3192 /* We want to quickly sample the PC. */
3193 if ((retval = target_halt(target)) != ERROR_OK)
3195 free(samples);
3196 return retval;
3198 } else
3200 command_print(CMD_CTX, "Target not halted or running");
3201 retval = ERROR_OK;
3202 break;
3204 if (retval != ERROR_OK)
3206 break;
3209 gettimeofday(&now, NULL);
3210 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3212 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3213 if ((retval = target_poll(target)) != ERROR_OK)
3215 free(samples);
3216 return retval;
3218 if (target->state == TARGET_HALTED)
3220 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3222 if ((retval = target_poll(target)) != ERROR_OK)
3224 free(samples);
3225 return retval;
3227 writeGmon(samples, numSamples, CMD_ARGV[1]);
3228 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3229 break;
3232 free(samples);
3234 return ERROR_OK;
3237 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3239 char *namebuf;
3240 Jim_Obj *nameObjPtr, *valObjPtr;
3241 int result;
3243 namebuf = alloc_printf("%s(%d)", varname, idx);
3244 if (!namebuf)
3245 return JIM_ERR;
3247 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3248 valObjPtr = Jim_NewIntObj(interp, val);
3249 if (!nameObjPtr || !valObjPtr)
3251 free(namebuf);
3252 return JIM_ERR;
3255 Jim_IncrRefCount(nameObjPtr);
3256 Jim_IncrRefCount(valObjPtr);
3257 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3258 Jim_DecrRefCount(interp, nameObjPtr);
3259 Jim_DecrRefCount(interp, valObjPtr);
3260 free(namebuf);
3261 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3262 return result;
3265 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3267 struct command_context *context;
3268 struct target *target;
3270 context = current_command_context(interp);
3271 assert (context != NULL);
3273 target = get_current_target(context);
3274 if (target == NULL)
3276 LOG_ERROR("mem2array: no current target");
3277 return JIM_ERR;
3280 return target_mem2array(interp, target, argc-1, argv + 1);
3283 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3285 long l;
3286 uint32_t width;
3287 int len;
3288 uint32_t addr;
3289 uint32_t count;
3290 uint32_t v;
3291 const char *varname;
3292 int n, e, retval;
3293 uint32_t i;
3295 /* argv[1] = name of array to receive the data
3296 * argv[2] = desired width
3297 * argv[3] = memory address
3298 * argv[4] = count of times to read
3300 if (argc != 4) {
3301 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3302 return JIM_ERR;
3304 varname = Jim_GetString(argv[0], &len);
3305 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3307 e = Jim_GetLong(interp, argv[1], &l);
3308 width = l;
3309 if (e != JIM_OK) {
3310 return e;
3313 e = Jim_GetLong(interp, argv[2], &l);
3314 addr = l;
3315 if (e != JIM_OK) {
3316 return e;
3318 e = Jim_GetLong(interp, argv[3], &l);
3319 len = l;
3320 if (e != JIM_OK) {
3321 return e;
3323 switch (width) {
3324 case 8:
3325 width = 1;
3326 break;
3327 case 16:
3328 width = 2;
3329 break;
3330 case 32:
3331 width = 4;
3332 break;
3333 default:
3334 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3335 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3336 return JIM_ERR;
3338 if (len == 0) {
3339 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3340 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3341 return JIM_ERR;
3343 if ((addr + (len * width)) < addr) {
3344 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3345 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3346 return JIM_ERR;
3348 /* absurd transfer size? */
3349 if (len > 65536) {
3350 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3351 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3352 return JIM_ERR;
3355 if ((width == 1) ||
3356 ((width == 2) && ((addr & 1) == 0)) ||
3357 ((width == 4) && ((addr & 3) == 0))) {
3358 /* all is well */
3359 } else {
3360 char buf[100];
3361 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3362 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3363 addr,
3364 width);
3365 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3366 return JIM_ERR;
3369 /* Transfer loop */
3371 /* index counter */
3372 n = 0;
3374 size_t buffersize = 4096;
3375 uint8_t *buffer = malloc(buffersize);
3376 if (buffer == NULL)
3377 return JIM_ERR;
3379 /* assume ok */
3380 e = JIM_OK;
3381 while (len) {
3382 /* Slurp... in buffer size chunks */
3384 count = len; /* in objects.. */
3385 if (count > (buffersize/width)) {
3386 count = (buffersize/width);
3389 retval = target_read_memory(target, addr, width, count, buffer);
3390 if (retval != ERROR_OK) {
3391 /* BOO !*/
3392 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3393 (unsigned int)addr,
3394 (int)width,
3395 (int)count);
3396 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3397 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3398 e = JIM_ERR;
3399 len = 0;
3400 } else {
3401 v = 0; /* shut up gcc */
3402 for (i = 0 ;i < count ;i++, n++) {
3403 switch (width) {
3404 case 4:
3405 v = target_buffer_get_u32(target, &buffer[i*width]);
3406 break;
3407 case 2:
3408 v = target_buffer_get_u16(target, &buffer[i*width]);
3409 break;
3410 case 1:
3411 v = buffer[i] & 0x0ff;
3412 break;
3414 new_int_array_element(interp, varname, n, v);
3416 len -= count;
3420 free(buffer);
3422 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3424 return JIM_OK;
3427 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3429 char *namebuf;
3430 Jim_Obj *nameObjPtr, *valObjPtr;
3431 int result;
3432 long l;
3434 namebuf = alloc_printf("%s(%d)", varname, idx);
3435 if (!namebuf)
3436 return JIM_ERR;
3438 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3439 if (!nameObjPtr)
3441 free(namebuf);
3442 return JIM_ERR;
3445 Jim_IncrRefCount(nameObjPtr);
3446 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3447 Jim_DecrRefCount(interp, nameObjPtr);
3448 free(namebuf);
3449 if (valObjPtr == NULL)
3450 return JIM_ERR;
3452 result = Jim_GetLong(interp, valObjPtr, &l);
3453 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3454 *val = l;
3455 return result;
3458 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3460 struct command_context *context;
3461 struct target *target;
3463 context = current_command_context(interp);
3464 assert (context != NULL);
3466 target = get_current_target(context);
3467 if (target == NULL) {
3468 LOG_ERROR("array2mem: no current target");
3469 return JIM_ERR;
3472 return target_array2mem(interp,target, argc-1, argv + 1);
3475 static int target_array2mem(Jim_Interp *interp, struct target *target,
3476 int argc, Jim_Obj *const *argv)
3478 long l;
3479 uint32_t width;
3480 int len;
3481 uint32_t addr;
3482 uint32_t count;
3483 uint32_t v;
3484 const char *varname;
3485 int n, e, retval;
3486 uint32_t i;
3488 /* argv[1] = name of array to get the data
3489 * argv[2] = desired width
3490 * argv[3] = memory address
3491 * argv[4] = count to write
3493 if (argc != 4) {
3494 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3495 return JIM_ERR;
3497 varname = Jim_GetString(argv[0], &len);
3498 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3500 e = Jim_GetLong(interp, argv[1], &l);
3501 width = l;
3502 if (e != JIM_OK) {
3503 return e;
3506 e = Jim_GetLong(interp, argv[2], &l);
3507 addr = l;
3508 if (e != JIM_OK) {
3509 return e;
3511 e = Jim_GetLong(interp, argv[3], &l);
3512 len = l;
3513 if (e != JIM_OK) {
3514 return e;
3516 switch (width) {
3517 case 8:
3518 width = 1;
3519 break;
3520 case 16:
3521 width = 2;
3522 break;
3523 case 32:
3524 width = 4;
3525 break;
3526 default:
3527 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3528 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3529 return JIM_ERR;
3531 if (len == 0) {
3532 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3533 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3534 return JIM_ERR;
3536 if ((addr + (len * width)) < addr) {
3537 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3538 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3539 return JIM_ERR;
3541 /* absurd transfer size? */
3542 if (len > 65536) {
3543 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3544 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3545 return JIM_ERR;
3548 if ((width == 1) ||
3549 ((width == 2) && ((addr & 1) == 0)) ||
3550 ((width == 4) && ((addr & 3) == 0))) {
3551 /* all is well */
3552 } else {
3553 char buf[100];
3554 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3555 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3556 (unsigned int)addr,
3557 (int)width);
3558 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3559 return JIM_ERR;
3562 /* Transfer loop */
3564 /* index counter */
3565 n = 0;
3566 /* assume ok */
3567 e = JIM_OK;
3569 size_t buffersize = 4096;
3570 uint8_t *buffer = malloc(buffersize);
3571 if (buffer == NULL)
3572 return JIM_ERR;
3574 while (len) {
3575 /* Slurp... in buffer size chunks */
3577 count = len; /* in objects.. */
3578 if (count > (buffersize/width)) {
3579 count = (buffersize/width);
3582 v = 0; /* shut up gcc */
3583 for (i = 0 ;i < count ;i++, n++) {
3584 get_int_array_element(interp, varname, n, &v);
3585 switch (width) {
3586 case 4:
3587 target_buffer_set_u32(target, &buffer[i*width], v);
3588 break;
3589 case 2:
3590 target_buffer_set_u16(target, &buffer[i*width], v);
3591 break;
3592 case 1:
3593 buffer[i] = v & 0x0ff;
3594 break;
3597 len -= count;
3599 retval = target_write_memory(target, addr, width, count, buffer);
3600 if (retval != ERROR_OK) {
3601 /* BOO !*/
3602 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3603 (unsigned int)addr,
3604 (int)width,
3605 (int)count);
3606 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3607 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3608 e = JIM_ERR;
3609 len = 0;
3613 free(buffer);
3615 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3617 return JIM_OK;
3620 /* FIX? should we propagate errors here rather than printing them
3621 * and continuing?
3623 void target_handle_event(struct target *target, enum target_event e)
3625 struct target_event_action *teap;
3627 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3628 if (teap->event == e) {
3629 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3630 target->target_number,
3631 target_name(target),
3632 target_type_name(target),
3634 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3635 Jim_GetString(teap->body, NULL));
3636 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3638 Jim_PrintErrorMessage(teap->interp);
3645 * Returns true only if the target has a handler for the specified event.
3647 bool target_has_event_action(struct target *target, enum target_event event)
3649 struct target_event_action *teap;
3651 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3652 if (teap->event == event)
3653 return true;
3655 return false;
3658 enum target_cfg_param {
3659 TCFG_TYPE,
3660 TCFG_EVENT,
3661 TCFG_WORK_AREA_VIRT,
3662 TCFG_WORK_AREA_PHYS,
3663 TCFG_WORK_AREA_SIZE,
3664 TCFG_WORK_AREA_BACKUP,
3665 TCFG_ENDIAN,
3666 TCFG_VARIANT,
3667 TCFG_CHAIN_POSITION,
3670 static Jim_Nvp nvp_config_opts[] = {
3671 { .name = "-type", .value = TCFG_TYPE },
3672 { .name = "-event", .value = TCFG_EVENT },
3673 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3674 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3675 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3676 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3677 { .name = "-endian" , .value = TCFG_ENDIAN },
3678 { .name = "-variant", .value = TCFG_VARIANT },
3679 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3681 { .name = NULL, .value = -1 }
3684 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3686 Jim_Nvp *n;
3687 Jim_Obj *o;
3688 jim_wide w;
3689 char *cp;
3690 int e;
3692 /* parse config or cget options ... */
3693 while (goi->argc > 0) {
3694 Jim_SetEmptyResult(goi->interp);
3695 /* Jim_GetOpt_Debug(goi); */
3697 if (target->type->target_jim_configure) {
3698 /* target defines a configure function */
3699 /* target gets first dibs on parameters */
3700 e = (*(target->type->target_jim_configure))(target, goi);
3701 if (e == JIM_OK) {
3702 /* more? */
3703 continue;
3705 if (e == JIM_ERR) {
3706 /* An error */
3707 return e;
3709 /* otherwise we 'continue' below */
3711 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3712 if (e != JIM_OK) {
3713 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3714 return e;
3716 switch (n->value) {
3717 case TCFG_TYPE:
3718 /* not setable */
3719 if (goi->isconfigure) {
3720 Jim_SetResult_sprintf(goi->interp,
3721 "not settable: %s", n->name);
3722 return JIM_ERR;
3723 } else {
3724 no_params:
3725 if (goi->argc != 0) {
3726 Jim_WrongNumArgs(goi->interp,
3727 goi->argc, goi->argv,
3728 "NO PARAMS");
3729 return JIM_ERR;
3732 Jim_SetResultString(goi->interp,
3733 target_type_name(target), -1);
3734 /* loop for more */
3735 break;
3736 case TCFG_EVENT:
3737 if (goi->argc == 0) {
3738 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3739 return JIM_ERR;
3742 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3743 if (e != JIM_OK) {
3744 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3745 return e;
3748 if (goi->isconfigure) {
3749 if (goi->argc != 1) {
3750 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3751 return JIM_ERR;
3753 } else {
3754 if (goi->argc != 0) {
3755 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3756 return JIM_ERR;
3761 struct target_event_action *teap;
3763 teap = target->event_action;
3764 /* replace existing? */
3765 while (teap) {
3766 if (teap->event == (enum target_event)n->value) {
3767 break;
3769 teap = teap->next;
3772 if (goi->isconfigure) {
3773 bool replace = true;
3774 if (teap == NULL) {
3775 /* create new */
3776 teap = calloc(1, sizeof(*teap));
3777 replace = false;
3779 teap->event = n->value;
3780 teap->interp = goi->interp;
3781 Jim_GetOpt_Obj(goi, &o);
3782 if (teap->body) {
3783 Jim_DecrRefCount(teap->interp, teap->body);
3785 teap->body = Jim_DuplicateObj(goi->interp, o);
3787 * FIXME:
3788 * Tcl/TK - "tk events" have a nice feature.
3789 * See the "BIND" command.
3790 * We should support that here.
3791 * You can specify %X and %Y in the event code.
3792 * The idea is: %T - target name.
3793 * The idea is: %N - target number
3794 * The idea is: %E - event name.
3796 Jim_IncrRefCount(teap->body);
3798 if (!replace)
3800 /* add to head of event list */
3801 teap->next = target->event_action;
3802 target->event_action = teap;
3804 Jim_SetEmptyResult(goi->interp);
3805 } else {
3806 /* get */
3807 if (teap == NULL) {
3808 Jim_SetEmptyResult(goi->interp);
3809 } else {
3810 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3814 /* loop for more */
3815 break;
3817 case TCFG_WORK_AREA_VIRT:
3818 if (goi->isconfigure) {
3819 target_free_all_working_areas(target);
3820 e = Jim_GetOpt_Wide(goi, &w);
3821 if (e != JIM_OK) {
3822 return e;
3824 target->working_area_virt = w;
3825 target->working_area_virt_spec = true;
3826 } else {
3827 if (goi->argc != 0) {
3828 goto no_params;
3831 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3832 /* loop for more */
3833 break;
3835 case TCFG_WORK_AREA_PHYS:
3836 if (goi->isconfigure) {
3837 target_free_all_working_areas(target);
3838 e = Jim_GetOpt_Wide(goi, &w);
3839 if (e != JIM_OK) {
3840 return e;
3842 target->working_area_phys = w;
3843 target->working_area_phys_spec = true;
3844 } else {
3845 if (goi->argc != 0) {
3846 goto no_params;
3849 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3850 /* loop for more */
3851 break;
3853 case TCFG_WORK_AREA_SIZE:
3854 if (goi->isconfigure) {
3855 target_free_all_working_areas(target);
3856 e = Jim_GetOpt_Wide(goi, &w);
3857 if (e != JIM_OK) {
3858 return e;
3860 target->working_area_size = w;
3861 } else {
3862 if (goi->argc != 0) {
3863 goto no_params;
3866 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3867 /* loop for more */
3868 break;
3870 case TCFG_WORK_AREA_BACKUP:
3871 if (goi->isconfigure) {
3872 target_free_all_working_areas(target);
3873 e = Jim_GetOpt_Wide(goi, &w);
3874 if (e != JIM_OK) {
3875 return e;
3877 /* make this exactly 1 or 0 */
3878 target->backup_working_area = (!!w);
3879 } else {
3880 if (goi->argc != 0) {
3881 goto no_params;
3884 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3885 /* loop for more e*/
3886 break;
3888 case TCFG_ENDIAN:
3889 if (goi->isconfigure) {
3890 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3891 if (e != JIM_OK) {
3892 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3893 return e;
3895 target->endianness = n->value;
3896 } else {
3897 if (goi->argc != 0) {
3898 goto no_params;
3901 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3902 if (n->name == NULL) {
3903 target->endianness = TARGET_LITTLE_ENDIAN;
3904 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3906 Jim_SetResultString(goi->interp, n->name, -1);
3907 /* loop for more */
3908 break;
3910 case TCFG_VARIANT:
3911 if (goi->isconfigure) {
3912 if (goi->argc < 1) {
3913 Jim_SetResult_sprintf(goi->interp,
3914 "%s ?STRING?",
3915 n->name);
3916 return JIM_ERR;
3918 if (target->variant) {
3919 free((void *)(target->variant));
3921 e = Jim_GetOpt_String(goi, &cp, NULL);
3922 target->variant = strdup(cp);
3923 } else {
3924 if (goi->argc != 0) {
3925 goto no_params;
3928 Jim_SetResultString(goi->interp, target->variant,-1);
3929 /* loop for more */
3930 break;
3931 case TCFG_CHAIN_POSITION:
3932 if (goi->isconfigure) {
3933 Jim_Obj *o_t;
3934 struct jtag_tap *tap;
3935 target_free_all_working_areas(target);
3936 e = Jim_GetOpt_Obj(goi, &o_t);
3937 if (e != JIM_OK) {
3938 return e;
3940 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
3941 if (tap == NULL) {
3942 return JIM_ERR;
3944 /* make this exactly 1 or 0 */
3945 target->tap = tap;
3946 } else {
3947 if (goi->argc != 0) {
3948 goto no_params;
3951 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
3952 /* loop for more e*/
3953 break;
3955 } /* while (goi->argc) */
3958 /* done - we return */
3959 return JIM_OK;
3962 static int
3963 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3965 Jim_GetOptInfo goi;
3967 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3968 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
3969 int need_args = 1 + goi.isconfigure;
3970 if (goi.argc < need_args)
3972 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
3973 goi.isconfigure
3974 ? "missing: -option VALUE ..."
3975 : "missing: -option ...");
3976 return JIM_ERR;
3978 struct target *target = Jim_CmdPrivData(goi.interp);
3979 return target_configure(&goi, target);
3982 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3984 const char *cmd_name = Jim_GetString(argv[0], NULL);
3986 Jim_GetOptInfo goi;
3987 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3989 if (goi.argc < 2 || goi.argc > 4)
3991 Jim_SetResult_sprintf(goi.interp,
3992 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
3993 return JIM_ERR;
3996 target_write_fn fn;
3997 fn = target_write_memory_fast;
3999 int e;
4000 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4002 /* consume it */
4003 struct Jim_Obj *obj;
4004 e = Jim_GetOpt_Obj(&goi, &obj);
4005 if (e != JIM_OK)
4006 return e;
4008 fn = target_write_phys_memory;
4011 jim_wide a;
4012 e = Jim_GetOpt_Wide(&goi, &a);
4013 if (e != JIM_OK)
4014 return e;
4016 jim_wide b;
4017 e = Jim_GetOpt_Wide(&goi, &b);
4018 if (e != JIM_OK)
4019 return e;
4021 jim_wide c = 1;
4022 if (goi.argc == 1)
4024 e = Jim_GetOpt_Wide(&goi, &c);
4025 if (e != JIM_OK)
4026 return e;
4029 /* all args must be consumed */
4030 if (goi.argc != 0)
4032 return JIM_ERR;
4035 struct target *target = Jim_CmdPrivData(goi.interp);
4036 unsigned data_size;
4037 if (strcasecmp(cmd_name, "mww") == 0) {
4038 data_size = 4;
4040 else if (strcasecmp(cmd_name, "mwh") == 0) {
4041 data_size = 2;
4043 else if (strcasecmp(cmd_name, "mwb") == 0) {
4044 data_size = 1;
4045 } else {
4046 LOG_ERROR("command '%s' unknown: ", cmd_name);
4047 return JIM_ERR;
4050 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4053 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4055 const char *cmd_name = Jim_GetString(argv[0], NULL);
4057 Jim_GetOptInfo goi;
4058 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4060 if ((goi.argc < 1) || (goi.argc > 3))
4062 Jim_SetResult_sprintf(goi.interp,
4063 "usage: %s [phys] <address> [<count>]", cmd_name);
4064 return JIM_ERR;
4067 int (*fn)(struct target *target,
4068 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4069 fn=target_read_memory;
4071 int e;
4072 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4074 /* consume it */
4075 struct Jim_Obj *obj;
4076 e = Jim_GetOpt_Obj(&goi, &obj);
4077 if (e != JIM_OK)
4078 return e;
4080 fn=target_read_phys_memory;
4083 jim_wide a;
4084 e = Jim_GetOpt_Wide(&goi, &a);
4085 if (e != JIM_OK) {
4086 return JIM_ERR;
4088 jim_wide c;
4089 if (goi.argc == 1) {
4090 e = Jim_GetOpt_Wide(&goi, &c);
4091 if (e != JIM_OK) {
4092 return JIM_ERR;
4094 } else {
4095 c = 1;
4098 /* all args must be consumed */
4099 if (goi.argc != 0)
4101 return JIM_ERR;
4104 jim_wide b = 1; /* shut up gcc */
4105 if (strcasecmp(cmd_name, "mdw") == 0)
4106 b = 4;
4107 else if (strcasecmp(cmd_name, "mdh") == 0)
4108 b = 2;
4109 else if (strcasecmp(cmd_name, "mdb") == 0)
4110 b = 1;
4111 else {
4112 LOG_ERROR("command '%s' unknown: ", cmd_name);
4113 return JIM_ERR;
4116 /* convert count to "bytes" */
4117 c = c * b;
4119 struct target *target = Jim_CmdPrivData(goi.interp);
4120 uint8_t target_buf[32];
4121 jim_wide x, y, z;
4122 while (c > 0) {
4123 y = c;
4124 if (y > 16) {
4125 y = 16;
4127 e = fn(target, a, b, y / b, target_buf);
4128 if (e != ERROR_OK) {
4129 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4130 return JIM_ERR;
4133 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4134 switch (b) {
4135 case 4:
4136 for (x = 0; x < 16 && x < y; x += 4)
4138 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4139 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4141 for (; (x < 16) ; x += 4) {
4142 Jim_fprintf(interp, interp->cookie_stdout, " ");
4144 break;
4145 case 2:
4146 for (x = 0; x < 16 && x < y; x += 2)
4148 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4149 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4151 for (; (x < 16) ; x += 2) {
4152 Jim_fprintf(interp, interp->cookie_stdout, " ");
4154 break;
4155 case 1:
4156 default:
4157 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4158 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4159 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4161 for (; (x < 16) ; x += 1) {
4162 Jim_fprintf(interp, interp->cookie_stdout, " ");
4164 break;
4166 /* ascii-ify the bytes */
4167 for (x = 0 ; x < y ; x++) {
4168 if ((target_buf[x] >= 0x20) &&
4169 (target_buf[x] <= 0x7e)) {
4170 /* good */
4171 } else {
4172 /* smack it */
4173 target_buf[x] = '.';
4176 /* space pad */
4177 while (x < 16) {
4178 target_buf[x] = ' ';
4179 x++;
4181 /* terminate */
4182 target_buf[16] = 0;
4183 /* print - with a newline */
4184 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4185 /* NEXT... */
4186 c -= 16;
4187 a += 16;
4189 return JIM_OK;
4192 static int jim_target_mem2array(Jim_Interp *interp,
4193 int argc, Jim_Obj *const *argv)
4195 struct target *target = Jim_CmdPrivData(interp);
4196 return target_mem2array(interp, target, argc - 1, argv + 1);
4199 static int jim_target_array2mem(Jim_Interp *interp,
4200 int argc, Jim_Obj *const *argv)
4202 struct target *target = Jim_CmdPrivData(interp);
4203 return target_array2mem(interp, target, argc - 1, argv + 1);
4206 static int jim_target_tap_disabled(Jim_Interp *interp)
4208 Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4209 return JIM_ERR;
4212 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4214 if (argc != 1)
4216 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4217 return JIM_ERR;
4219 struct target *target = Jim_CmdPrivData(interp);
4220 if (!target->tap->enabled)
4221 return jim_target_tap_disabled(interp);
4223 int e = target->type->examine(target);
4224 if (e != ERROR_OK)
4226 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4227 return JIM_ERR;
4229 return JIM_OK;
4232 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4234 if (argc != 1)
4236 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4237 return JIM_ERR;
4239 struct target *target = Jim_CmdPrivData(interp);
4241 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4242 return JIM_ERR;
4244 return JIM_OK;
4247 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4249 if (argc != 1)
4251 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4252 return JIM_ERR;
4254 struct target *target = Jim_CmdPrivData(interp);
4255 if (!target->tap->enabled)
4256 return jim_target_tap_disabled(interp);
4258 int e;
4259 if (!(target_was_examined(target))) {
4260 e = ERROR_TARGET_NOT_EXAMINED;
4261 } else {
4262 e = target->type->poll(target);
4264 if (e != ERROR_OK)
4266 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4267 return JIM_ERR;
4269 return JIM_OK;
4272 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4274 Jim_GetOptInfo goi;
4275 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4277 if (goi.argc != 2)
4279 Jim_WrongNumArgs(interp, 0, argv,
4280 "([tT]|[fF]|assert|deassert) BOOL");
4281 return JIM_ERR;
4284 Jim_Nvp *n;
4285 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4286 if (e != JIM_OK)
4288 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4289 return e;
4291 /* the halt or not param */
4292 jim_wide a;
4293 e = Jim_GetOpt_Wide(&goi, &a);
4294 if (e != JIM_OK)
4295 return e;
4297 struct target *target = Jim_CmdPrivData(goi.interp);
4298 if (!target->tap->enabled)
4299 return jim_target_tap_disabled(interp);
4300 if (!(target_was_examined(target)))
4302 LOG_ERROR("Target not examined yet");
4303 return ERROR_TARGET_NOT_EXAMINED;
4305 if (!target->type->assert_reset || !target->type->deassert_reset)
4307 Jim_SetResult_sprintf(interp,
4308 "No target-specific reset for %s",
4309 target_name(target));
4310 return JIM_ERR;
4312 /* determine if we should halt or not. */
4313 target->reset_halt = !!a;
4314 /* When this happens - all workareas are invalid. */
4315 target_free_all_working_areas_restore(target, 0);
4317 /* do the assert */
4318 if (n->value == NVP_ASSERT) {
4319 e = target->type->assert_reset(target);
4320 } else {
4321 e = target->type->deassert_reset(target);
4323 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4326 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4328 if (argc != 1) {
4329 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4330 return JIM_ERR;
4332 struct target *target = Jim_CmdPrivData(interp);
4333 if (!target->tap->enabled)
4334 return jim_target_tap_disabled(interp);
4335 int e = target->type->halt(target);
4336 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4339 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4341 Jim_GetOptInfo goi;
4342 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4344 /* params: <name> statename timeoutmsecs */
4345 if (goi.argc != 2)
4347 const char *cmd_name = Jim_GetString(argv[0], NULL);
4348 Jim_SetResult_sprintf(goi.interp,
4349 "%s <state_name> <timeout_in_msec>", cmd_name);
4350 return JIM_ERR;
4353 Jim_Nvp *n;
4354 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4355 if (e != JIM_OK) {
4356 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4357 return e;
4359 jim_wide a;
4360 e = Jim_GetOpt_Wide(&goi, &a);
4361 if (e != JIM_OK) {
4362 return e;
4364 struct target *target = Jim_CmdPrivData(interp);
4365 if (!target->tap->enabled)
4366 return jim_target_tap_disabled(interp);
4368 e = target_wait_state(target, n->value, a);
4369 if (e != ERROR_OK)
4371 Jim_SetResult_sprintf(goi.interp,
4372 "target: %s wait %s fails (%d) %s",
4373 target_name(target), n->name,
4374 e, target_strerror_safe(e));
4375 return JIM_ERR;
4377 return JIM_OK;
4379 /* List for human, Events defined for this target.
4380 * scripts/programs should use 'name cget -event NAME'
4382 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4384 struct command_context *cmd_ctx = current_command_context(interp);
4385 assert (cmd_ctx != NULL);
4387 struct target *target = Jim_CmdPrivData(interp);
4388 struct target_event_action *teap = target->event_action;
4389 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4390 target->target_number,
4391 target_name(target));
4392 command_print(cmd_ctx, "%-25s | Body", "Event");
4393 command_print(cmd_ctx, "------------------------- | "
4394 "----------------------------------------");
4395 while (teap)
4397 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4398 command_print(cmd_ctx, "%-25s | %s",
4399 opt->name, Jim_GetString(teap->body, NULL));
4400 teap = teap->next;
4402 command_print(cmd_ctx, "***END***");
4403 return JIM_OK;
4405 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4407 if (argc != 1)
4409 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4410 return JIM_ERR;
4412 struct target *target = Jim_CmdPrivData(interp);
4413 Jim_SetResultString(interp, target_state_name(target), -1);
4414 return JIM_OK;
4416 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4418 Jim_GetOptInfo goi;
4419 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4420 if (goi.argc != 1)
4422 const char *cmd_name = Jim_GetString(argv[0], NULL);
4423 Jim_SetResult_sprintf(goi.interp, "%s <eventname>", cmd_name);
4424 return JIM_ERR;
4426 Jim_Nvp *n;
4427 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4428 if (e != JIM_OK)
4430 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4431 return e;
4433 struct target *target = Jim_CmdPrivData(interp);
4434 target_handle_event(target, n->value);
4435 return JIM_OK;
4438 static const struct command_registration target_instance_command_handlers[] = {
4440 .name = "configure",
4441 .mode = COMMAND_CONFIG,
4442 .jim_handler = jim_target_configure,
4443 .help = "configure a new target for use",
4444 .usage = "[target_attribute ...]",
4447 .name = "cget",
4448 .mode = COMMAND_ANY,
4449 .jim_handler = jim_target_configure,
4450 .help = "returns the specified target attribute",
4451 .usage = "target_attribute",
4454 .name = "mww",
4455 .mode = COMMAND_EXEC,
4456 .jim_handler = jim_target_mw,
4457 .help = "Write 32-bit word(s) to target memory",
4458 .usage = "address data [count]",
4461 .name = "mwh",
4462 .mode = COMMAND_EXEC,
4463 .jim_handler = jim_target_mw,
4464 .help = "Write 16-bit half-word(s) to target memory",
4465 .usage = "address data [count]",
4468 .name = "mwb",
4469 .mode = COMMAND_EXEC,
4470 .jim_handler = jim_target_mw,
4471 .help = "Write byte(s) to target memory",
4472 .usage = "address data [count]",
4475 .name = "mdw",
4476 .mode = COMMAND_EXEC,
4477 .jim_handler = jim_target_md,
4478 .help = "Display target memory as 32-bit words",
4479 .usage = "address [count]",
4482 .name = "mdh",
4483 .mode = COMMAND_EXEC,
4484 .jim_handler = jim_target_md,
4485 .help = "Display target memory as 16-bit half-words",
4486 .usage = "address [count]",
4489 .name = "mdb",
4490 .mode = COMMAND_EXEC,
4491 .jim_handler = jim_target_md,
4492 .help = "Display target memory as 8-bit bytes",
4493 .usage = "address [count]",
4496 .name = "array2mem",
4497 .mode = COMMAND_EXEC,
4498 .jim_handler = jim_target_array2mem,
4499 .help = "Writes Tcl array of 8/16/32 bit numbers "
4500 "to target memory",
4501 .usage = "arrayname bitwidth address count",
4504 .name = "mem2array",
4505 .mode = COMMAND_EXEC,
4506 .jim_handler = jim_target_mem2array,
4507 .help = "Loads Tcl array of 8/16/32 bit numbers "
4508 "from target memory",
4509 .usage = "arrayname bitwidth address count",
4512 .name = "eventlist",
4513 .mode = COMMAND_EXEC,
4514 .jim_handler = jim_target_event_list,
4515 .help = "displays a table of events defined for this target",
4518 .name = "curstate",
4519 .mode = COMMAND_EXEC,
4520 .jim_handler = jim_target_current_state,
4521 .help = "displays the current state of this target",
4524 .name = "arp_examine",
4525 .mode = COMMAND_EXEC,
4526 .jim_handler = jim_target_examine,
4527 .help = "used internally for reset processing",
4530 .name = "arp_halt_gdb",
4531 .mode = COMMAND_EXEC,
4532 .jim_handler = jim_target_halt_gdb,
4533 .help = "used internally for reset processing to halt GDB",
4536 .name = "arp_poll",
4537 .mode = COMMAND_EXEC,
4538 .jim_handler = jim_target_poll,
4539 .help = "used internally for reset processing",
4542 .name = "arp_reset",
4543 .mode = COMMAND_EXEC,
4544 .jim_handler = jim_target_reset,
4545 .help = "used internally for reset processing",
4548 .name = "arp_halt",
4549 .mode = COMMAND_EXEC,
4550 .jim_handler = jim_target_halt,
4551 .help = "used internally for reset processing",
4554 .name = "arp_waitstate",
4555 .mode = COMMAND_EXEC,
4556 .jim_handler = jim_target_wait_state,
4557 .help = "used internally for reset processing",
4560 .name = "invoke-event",
4561 .mode = COMMAND_EXEC,
4562 .jim_handler = jim_target_invoke_event,
4563 .help = "invoke handler for specified event",
4564 .usage = "event_name",
4566 COMMAND_REGISTRATION_DONE
4569 static int target_create(Jim_GetOptInfo *goi)
4571 Jim_Obj *new_cmd;
4572 Jim_Cmd *cmd;
4573 const char *cp;
4574 char *cp2;
4575 int e;
4576 int x;
4577 struct target *target;
4578 struct command_context *cmd_ctx;
4580 cmd_ctx = current_command_context(goi->interp);
4581 assert (cmd_ctx != NULL);
4583 if (goi->argc < 3) {
4584 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4585 return JIM_ERR;
4588 /* COMMAND */
4589 Jim_GetOpt_Obj(goi, &new_cmd);
4590 /* does this command exist? */
4591 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4592 if (cmd) {
4593 cp = Jim_GetString(new_cmd, NULL);
4594 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4595 return JIM_ERR;
4598 /* TYPE */
4599 e = Jim_GetOpt_String(goi, &cp2, NULL);
4600 cp = cp2;
4601 /* now does target type exist */
4602 for (x = 0 ; target_types[x] ; x++) {
4603 if (0 == strcmp(cp, target_types[x]->name)) {
4604 /* found */
4605 break;
4608 if (target_types[x] == NULL) {
4609 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4610 for (x = 0 ; target_types[x] ; x++) {
4611 if (target_types[x + 1]) {
4612 Jim_AppendStrings(goi->interp,
4613 Jim_GetResult(goi->interp),
4614 target_types[x]->name,
4615 ", ", NULL);
4616 } else {
4617 Jim_AppendStrings(goi->interp,
4618 Jim_GetResult(goi->interp),
4619 " or ",
4620 target_types[x]->name,NULL);
4623 return JIM_ERR;
4626 /* Create it */
4627 target = calloc(1,sizeof(struct target));
4628 /* set target number */
4629 target->target_number = new_target_number();
4631 /* allocate memory for each unique target type */
4632 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4634 memcpy(target->type, target_types[x], sizeof(struct target_type));
4636 /* will be set by "-endian" */
4637 target->endianness = TARGET_ENDIAN_UNKNOWN;
4639 target->working_area = 0x0;
4640 target->working_area_size = 0x0;
4641 target->working_areas = NULL;
4642 target->backup_working_area = 0;
4644 target->state = TARGET_UNKNOWN;
4645 target->debug_reason = DBG_REASON_UNDEFINED;
4646 target->reg_cache = NULL;
4647 target->breakpoints = NULL;
4648 target->watchpoints = NULL;
4649 target->next = NULL;
4650 target->arch_info = NULL;
4652 target->display = 1;
4654 target->halt_issued = false;
4656 /* initialize trace information */
4657 target->trace_info = malloc(sizeof(struct trace));
4658 target->trace_info->num_trace_points = 0;
4659 target->trace_info->trace_points_size = 0;
4660 target->trace_info->trace_points = NULL;
4661 target->trace_info->trace_history_size = 0;
4662 target->trace_info->trace_history = NULL;
4663 target->trace_info->trace_history_pos = 0;
4664 target->trace_info->trace_history_overflowed = 0;
4666 target->dbgmsg = NULL;
4667 target->dbg_msg_enabled = 0;
4669 target->endianness = TARGET_ENDIAN_UNKNOWN;
4671 /* Do the rest as "configure" options */
4672 goi->isconfigure = 1;
4673 e = target_configure(goi, target);
4675 if (target->tap == NULL)
4677 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4678 e = JIM_ERR;
4681 if (e != JIM_OK) {
4682 free(target->type);
4683 free(target);
4684 return e;
4687 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4688 /* default endian to little if not specified */
4689 target->endianness = TARGET_LITTLE_ENDIAN;
4692 /* incase variant is not set */
4693 if (!target->variant)
4694 target->variant = strdup("");
4696 cp = Jim_GetString(new_cmd, NULL);
4697 target->cmd_name = strdup(cp);
4699 /* create the target specific commands */
4700 if (target->type->commands) {
4701 e = register_commands(cmd_ctx, NULL, target->type->commands);
4702 if (ERROR_OK != e)
4703 LOG_ERROR("unable to register '%s' commands", cp);
4705 if (target->type->target_create) {
4706 (*(target->type->target_create))(target, goi->interp);
4709 /* append to end of list */
4711 struct target **tpp;
4712 tpp = &(all_targets);
4713 while (*tpp) {
4714 tpp = &((*tpp)->next);
4716 *tpp = target;
4719 /* now - create the new target name command */
4720 const const struct command_registration target_subcommands[] = {
4722 .chain = target_instance_command_handlers,
4725 .chain = target->type->commands,
4727 COMMAND_REGISTRATION_DONE
4729 const const struct command_registration target_commands[] = {
4731 .name = cp,
4732 .mode = COMMAND_ANY,
4733 .help = "target command group",
4734 .chain = target_subcommands,
4736 COMMAND_REGISTRATION_DONE
4738 e = register_commands(cmd_ctx, NULL, target_commands);
4739 if (ERROR_OK != e)
4740 return JIM_ERR;
4742 struct command *c = command_find_in_context(cmd_ctx, cp);
4743 assert(c);
4744 command_set_handler_data(c, target);
4746 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4749 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4751 if (argc != 1)
4753 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4754 return JIM_ERR;
4756 struct command_context *cmd_ctx = current_command_context(interp);
4757 assert (cmd_ctx != NULL);
4759 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4760 return JIM_OK;
4763 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4765 if (argc != 1)
4767 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4768 return JIM_ERR;
4770 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4771 for (unsigned x = 0; NULL != target_types[x]; x++)
4773 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4774 Jim_NewStringObj(interp, target_types[x]->name, -1));
4776 return JIM_OK;
4779 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4781 if (argc != 1)
4783 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4784 return JIM_ERR;
4786 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4787 struct target *target = all_targets;
4788 while (target)
4790 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4791 Jim_NewStringObj(interp, target_name(target), -1));
4792 target = target->next;
4794 return JIM_OK;
4797 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4799 Jim_GetOptInfo goi;
4800 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4801 if (goi.argc < 3)
4803 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4804 "<name> <target_type> [<target_options> ...]");
4805 return JIM_ERR;
4807 return target_create(&goi);
4810 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4812 Jim_GetOptInfo goi;
4813 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4815 /* It's OK to remove this mechanism sometime after August 2010 or so */
4816 LOG_WARNING("don't use numbers as target identifiers; use names");
4817 if (goi.argc != 1)
4819 Jim_SetResult_sprintf(goi.interp, "usage: target number <number>");
4820 return JIM_ERR;
4822 jim_wide w;
4823 int e = Jim_GetOpt_Wide(&goi, &w);
4824 if (e != JIM_OK)
4825 return JIM_ERR;
4827 struct target *target;
4828 for (target = all_targets; NULL != target; target = target->next)
4830 if (target->target_number != w)
4831 continue;
4833 Jim_SetResultString(goi.interp, target_name(target), -1);
4834 return JIM_OK;
4836 Jim_SetResult_sprintf(goi.interp,
4837 "Target: number %d does not exist", (int)(w));
4838 return JIM_ERR;
4841 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4843 if (argc != 1)
4845 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4846 return JIM_ERR;
4848 unsigned count = 0;
4849 struct target *target = all_targets;
4850 while (NULL != target)
4852 target = target->next;
4853 count++;
4855 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4856 return JIM_OK;
4859 static const struct command_registration target_subcommand_handlers[] = {
4861 .name = "init",
4862 .mode = COMMAND_CONFIG,
4863 .handler = handle_target_init_command,
4864 .help = "initialize targets",
4867 .name = "create",
4868 /* REVISIT this should be COMMAND_CONFIG ... */
4869 .mode = COMMAND_ANY,
4870 .jim_handler = jim_target_create,
4871 .usage = "name type '-chain-position' name [options ...]",
4872 .help = "Creates and selects a new target",
4875 .name = "current",
4876 .mode = COMMAND_ANY,
4877 .jim_handler = jim_target_current,
4878 .help = "Returns the currently selected target",
4881 .name = "types",
4882 .mode = COMMAND_ANY,
4883 .jim_handler = jim_target_types,
4884 .help = "Returns the available target types as "
4885 "a list of strings",
4888 .name = "names",
4889 .mode = COMMAND_ANY,
4890 .jim_handler = jim_target_names,
4891 .help = "Returns the names of all targets as a list of strings",
4894 .name = "number",
4895 .mode = COMMAND_ANY,
4896 .jim_handler = jim_target_number,
4897 .usage = "number",
4898 .help = "Returns the name of the numbered target "
4899 "(DEPRECATED)",
4902 .name = "count",
4903 .mode = COMMAND_ANY,
4904 .jim_handler = jim_target_count,
4905 .help = "Returns the number of targets as an integer "
4906 "(DEPRECATED)",
4908 COMMAND_REGISTRATION_DONE
4911 struct FastLoad
4913 uint32_t address;
4914 uint8_t *data;
4915 int length;
4919 static int fastload_num;
4920 static struct FastLoad *fastload;
4922 static void free_fastload(void)
4924 if (fastload != NULL)
4926 int i;
4927 for (i = 0; i < fastload_num; i++)
4929 if (fastload[i].data)
4930 free(fastload[i].data);
4932 free(fastload);
4933 fastload = NULL;
4940 COMMAND_HANDLER(handle_fast_load_image_command)
4942 uint8_t *buffer;
4943 size_t buf_cnt;
4944 uint32_t image_size;
4945 uint32_t min_address = 0;
4946 uint32_t max_address = 0xffffffff;
4947 int i;
4949 struct image image;
4951 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4952 &image, &min_address, &max_address);
4953 if (ERROR_OK != retval)
4954 return retval;
4956 struct duration bench;
4957 duration_start(&bench);
4959 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
4961 return ERROR_OK;
4964 image_size = 0x0;
4965 retval = ERROR_OK;
4966 fastload_num = image.num_sections;
4967 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4968 if (fastload == NULL)
4970 image_close(&image);
4971 return ERROR_FAIL;
4973 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4974 for (i = 0; i < image.num_sections; i++)
4976 buffer = malloc(image.sections[i].size);
4977 if (buffer == NULL)
4979 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
4980 (int)(image.sections[i].size));
4981 break;
4984 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4986 free(buffer);
4987 break;
4990 uint32_t offset = 0;
4991 uint32_t length = buf_cnt;
4994 /* DANGER!!! beware of unsigned comparision here!!! */
4996 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4997 (image.sections[i].base_address < max_address))
4999 if (image.sections[i].base_address < min_address)
5001 /* clip addresses below */
5002 offset += min_address-image.sections[i].base_address;
5003 length -= offset;
5006 if (image.sections[i].base_address + buf_cnt > max_address)
5008 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5011 fastload[i].address = image.sections[i].base_address + offset;
5012 fastload[i].data = malloc(length);
5013 if (fastload[i].data == NULL)
5015 free(buffer);
5016 break;
5018 memcpy(fastload[i].data, buffer + offset, length);
5019 fastload[i].length = length;
5021 image_size += length;
5022 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5023 (unsigned int)length,
5024 ((unsigned int)(image.sections[i].base_address + offset)));
5027 free(buffer);
5030 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5032 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5033 "in %fs (%0.3f KiB/s)", image_size,
5034 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5036 command_print(CMD_CTX,
5037 "WARNING: image has not been loaded to target!"
5038 "You can issue a 'fast_load' to finish loading.");
5041 image_close(&image);
5043 if (retval != ERROR_OK)
5045 free_fastload();
5048 return retval;
5051 COMMAND_HANDLER(handle_fast_load_command)
5053 if (CMD_ARGC > 0)
5054 return ERROR_COMMAND_SYNTAX_ERROR;
5055 if (fastload == NULL)
5057 LOG_ERROR("No image in memory");
5058 return ERROR_FAIL;
5060 int i;
5061 int ms = timeval_ms();
5062 int size = 0;
5063 int retval = ERROR_OK;
5064 for (i = 0; i < fastload_num;i++)
5066 struct target *target = get_current_target(CMD_CTX);
5067 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5068 (unsigned int)(fastload[i].address),
5069 (unsigned int)(fastload[i].length));
5070 if (retval == ERROR_OK)
5072 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5074 size += fastload[i].length;
5076 int after = timeval_ms();
5077 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5078 return retval;
5081 static const struct command_registration target_command_handlers[] = {
5083 .name = "targets",
5084 .handler = handle_targets_command,
5085 .mode = COMMAND_ANY,
5086 .help = "change current default target (one parameter) "
5087 "or prints table of all targets (no parameters)",
5088 .usage = "[target]",
5091 .name = "target",
5092 .mode = COMMAND_CONFIG,
5093 .help = "configure target",
5095 .chain = target_subcommand_handlers,
5097 COMMAND_REGISTRATION_DONE
5100 int target_register_commands(struct command_context *cmd_ctx)
5102 return register_commands(cmd_ctx, NULL, target_command_handlers);
5105 static bool target_reset_nag = true;
5107 bool get_target_reset_nag(void)
5109 return target_reset_nag;
5112 COMMAND_HANDLER(handle_target_reset_nag)
5114 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5115 &target_reset_nag, "Nag after each reset about options to improve "
5116 "performance");
5119 static const struct command_registration target_exec_command_handlers[] = {
5121 .name = "fast_load_image",
5122 .handler = handle_fast_load_image_command,
5123 .mode = COMMAND_ANY,
5124 .help = "Load image into server memory for later use by "
5125 "fast_load; primarily for profiling",
5126 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5127 "[min_address [max_length]]",
5130 .name = "fast_load",
5131 .handler = handle_fast_load_command,
5132 .mode = COMMAND_EXEC,
5133 .help = "loads active fast load image to current target "
5134 "- mainly for profiling purposes",
5137 .name = "profile",
5138 .handler = handle_profile_command,
5139 .mode = COMMAND_EXEC,
5140 .help = "profiling samples the CPU PC",
5142 /** @todo don't register virt2phys() unless target supports it */
5144 .name = "virt2phys",
5145 .handler = handle_virt2phys_command,
5146 .mode = COMMAND_ANY,
5147 .help = "translate a virtual address into a physical address",
5148 .usage = "virtual_address",
5151 .name = "reg",
5152 .handler = handle_reg_command,
5153 .mode = COMMAND_EXEC,
5154 .help = "display or set a register; with no arguments, "
5155 "displays all registers and their values",
5156 .usage = "[(register_name|register_number) [value]]",
5159 .name = "poll",
5160 .handler = handle_poll_command,
5161 .mode = COMMAND_EXEC,
5162 .help = "poll target state; or reconfigure background polling",
5163 .usage = "['on'|'off']",
5166 .name = "wait_halt",
5167 .handler = handle_wait_halt_command,
5168 .mode = COMMAND_EXEC,
5169 .help = "wait up to the specified number of milliseconds "
5170 "(default 5) for a previously requested halt",
5171 .usage = "[milliseconds]",
5174 .name = "halt",
5175 .handler = handle_halt_command,
5176 .mode = COMMAND_EXEC,
5177 .help = "request target to halt, then wait up to the specified"
5178 "number of milliseconds (default 5) for it to complete",
5179 .usage = "[milliseconds]",
5182 .name = "resume",
5183 .handler = handle_resume_command,
5184 .mode = COMMAND_EXEC,
5185 .help = "resume target execution from current PC or address",
5186 .usage = "[address]",
5189 .name = "reset",
5190 .handler = handle_reset_command,
5191 .mode = COMMAND_EXEC,
5192 .usage = "[run|halt|init]",
5193 .help = "Reset all targets into the specified mode."
5194 "Default reset mode is run, if not given.",
5197 .name = "soft_reset_halt",
5198 .handler = handle_soft_reset_halt_command,
5199 .mode = COMMAND_EXEC,
5200 .help = "halt the target and do a soft reset",
5203 .name = "step",
5204 .handler = handle_step_command,
5205 .mode = COMMAND_EXEC,
5206 .help = "step one instruction from current PC or address",
5207 .usage = "[address]",
5210 .name = "mdw",
5211 .handler = handle_md_command,
5212 .mode = COMMAND_EXEC,
5213 .help = "display memory words",
5214 .usage = "['phys'] address [count]",
5217 .name = "mdh",
5218 .handler = handle_md_command,
5219 .mode = COMMAND_EXEC,
5220 .help = "display memory half-words",
5221 .usage = "['phys'] address [count]",
5224 .name = "mdb",
5225 .handler = handle_md_command,
5226 .mode = COMMAND_EXEC,
5227 .help = "display memory bytes",
5228 .usage = "['phys'] address [count]",
5231 .name = "mww",
5232 .handler = handle_mw_command,
5233 .mode = COMMAND_EXEC,
5234 .help = "write memory word",
5235 .usage = "['phys'] address value [count]",
5238 .name = "mwh",
5239 .handler = handle_mw_command,
5240 .mode = COMMAND_EXEC,
5241 .help = "write memory half-word",
5242 .usage = "['phys'] address value [count]",
5245 .name = "mwb",
5246 .handler = handle_mw_command,
5247 .mode = COMMAND_EXEC,
5248 .help = "write memory byte",
5249 .usage = "['phys'] address value [count]",
5252 .name = "bp",
5253 .handler = handle_bp_command,
5254 .mode = COMMAND_EXEC,
5255 .help = "list or set hardware or software breakpoint",
5256 .usage = "[address length ['hw']]",
5259 .name = "rbp",
5260 .handler = handle_rbp_command,
5261 .mode = COMMAND_EXEC,
5262 .help = "remove breakpoint",
5263 .usage = "address",
5266 .name = "wp",
5267 .handler = handle_wp_command,
5268 .mode = COMMAND_EXEC,
5269 .help = "list (no params) or create watchpoints",
5270 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5273 .name = "rwp",
5274 .handler = handle_rwp_command,
5275 .mode = COMMAND_EXEC,
5276 .help = "remove watchpoint",
5277 .usage = "address",
5280 .name = "load_image",
5281 .handler = handle_load_image_command,
5282 .mode = COMMAND_EXEC,
5283 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5284 "[min_address] [max_length]",
5287 .name = "dump_image",
5288 .handler = handle_dump_image_command,
5289 .mode = COMMAND_EXEC,
5290 .usage = "filename address size",
5293 .name = "verify_image",
5294 .handler = handle_verify_image_command,
5295 .mode = COMMAND_EXEC,
5296 .usage = "filename [offset [type]]",
5299 .name = "test_image",
5300 .handler = handle_test_image_command,
5301 .mode = COMMAND_EXEC,
5302 .usage = "filename [offset [type]]",
5305 .name = "mem2array",
5306 .mode = COMMAND_EXEC,
5307 .jim_handler = jim_mem2array,
5308 .help = "read 8/16/32 bit memory and return as a TCL array "
5309 "for script processing",
5310 .usage = "arrayname bitwidth address count",
5313 .name = "array2mem",
5314 .mode = COMMAND_EXEC,
5315 .jim_handler = jim_array2mem,
5316 .help = "convert a TCL array to memory locations "
5317 "and write the 8/16/32 bit values",
5318 .usage = "arrayname bitwidth address count",
5321 .name = "reset_nag",
5322 .handler = handle_target_reset_nag,
5323 .mode = COMMAND_ANY,
5324 .help = "Nag after each reset about options that could have been "
5325 "enabled to improve performance. ",
5326 .usage = "['enable'|'disable']",
5328 COMMAND_REGISTRATION_DONE
5330 static int target_register_user_commands(struct command_context *cmd_ctx)
5332 int retval = ERROR_OK;
5333 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5334 return retval;
5336 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5337 return retval;
5340 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);