jim tests: use installed
[openocd.git] / src / target / target.c
blobd200ebc98427b2a3a71c0ed466ab9453eca9b1f6
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_MakeErrorMessage(cmd_ctx->interp);
509 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
510 return ERROR_FAIL;
513 /* We want any events to be processed before the prompt */
514 retval = target_call_timer_callbacks_now();
516 struct target *target;
517 for (target = all_targets; target; target = target->next) {
518 target->type->check_reset(target);
521 return retval;
524 static int identity_virt2phys(struct target *target,
525 uint32_t virtual, uint32_t *physical)
527 *physical = virtual;
528 return ERROR_OK;
531 static int no_mmu(struct target *target, int *enabled)
533 *enabled = 0;
534 return ERROR_OK;
537 static int default_examine(struct target *target)
539 target_set_examined(target);
540 return ERROR_OK;
543 /* no check by default */
544 static int default_check_reset(struct target *target)
546 return ERROR_OK;
549 int target_examine_one(struct target *target)
551 return target->type->examine(target);
554 static int jtag_enable_callback(enum jtag_event event, void *priv)
556 struct target *target = priv;
558 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
559 return ERROR_OK;
561 jtag_unregister_event_callback(jtag_enable_callback, target);
562 return target_examine_one(target);
566 /* Targets that correctly implement init + examine, i.e.
567 * no communication with target during init:
569 * XScale
571 int target_examine(void)
573 int retval = ERROR_OK;
574 struct target *target;
576 for (target = all_targets; target; target = target->next)
578 /* defer examination, but don't skip it */
579 if (!target->tap->enabled) {
580 jtag_register_event_callback(jtag_enable_callback,
581 target);
582 continue;
584 if ((retval = target_examine_one(target)) != ERROR_OK)
585 return retval;
587 return retval;
589 const char *target_type_name(struct target *target)
591 return target->type->name;
594 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
596 if (!target_was_examined(target))
598 LOG_ERROR("Target not examined yet");
599 return ERROR_FAIL;
601 return target->type->write_memory_imp(target, address, size, count, buffer);
604 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
606 if (!target_was_examined(target))
608 LOG_ERROR("Target not examined yet");
609 return ERROR_FAIL;
611 return target->type->read_memory_imp(target, address, size, count, buffer);
614 static int target_soft_reset_halt_imp(struct target *target)
616 if (!target_was_examined(target))
618 LOG_ERROR("Target not examined yet");
619 return ERROR_FAIL;
621 if (!target->type->soft_reset_halt_imp) {
622 LOG_ERROR("Target %s does not support soft_reset_halt",
623 target_name(target));
624 return ERROR_FAIL;
626 return target->type->soft_reset_halt_imp(target);
630 * Downloads a target-specific native code algorithm to the target,
631 * and executes it. * Note that some targets may need to set up, enable,
632 * and tear down a breakpoint (hard or * soft) to detect algorithm
633 * termination, while others may support lower overhead schemes where
634 * soft breakpoints embedded in the algorithm automatically terminate the
635 * algorithm.
637 * @param target used to run the algorithm
638 * @param arch_info target-specific description of the algorithm.
640 int target_run_algorithm(struct target *target,
641 int num_mem_params, struct mem_param *mem_params,
642 int num_reg_params, struct reg_param *reg_param,
643 uint32_t entry_point, uint32_t exit_point,
644 int timeout_ms, void *arch_info)
646 int retval = ERROR_FAIL;
648 if (!target_was_examined(target))
650 LOG_ERROR("Target not examined yet");
651 goto done;
653 if (!target->type->run_algorithm) {
654 LOG_ERROR("Target type '%s' does not support %s",
655 target_type_name(target), __func__);
656 goto done;
659 target->running_alg = true;
660 retval = target->type->run_algorithm(target,
661 num_mem_params, mem_params,
662 num_reg_params, reg_param,
663 entry_point, exit_point, timeout_ms, arch_info);
664 target->running_alg = false;
666 done:
667 return retval;
671 int target_read_memory(struct target *target,
672 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
674 return target->type->read_memory(target, address, size, count, buffer);
677 static int target_read_phys_memory(struct target *target,
678 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
680 return target->type->read_phys_memory(target, address, size, count, buffer);
683 int target_write_memory(struct target *target,
684 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
686 return target->type->write_memory(target, address, size, count, buffer);
689 static int target_write_phys_memory(struct target *target,
690 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
692 return target->type->write_phys_memory(target, address, size, count, buffer);
695 int target_bulk_write_memory(struct target *target,
696 uint32_t address, uint32_t count, uint8_t *buffer)
698 return target->type->bulk_write_memory(target, address, count, buffer);
701 int target_add_breakpoint(struct target *target,
702 struct breakpoint *breakpoint)
704 if (target->state != TARGET_HALTED) {
705 LOG_WARNING("target %s is not halted", target->cmd_name);
706 return ERROR_TARGET_NOT_HALTED;
708 return target->type->add_breakpoint(target, breakpoint);
710 int target_remove_breakpoint(struct target *target,
711 struct breakpoint *breakpoint)
713 return target->type->remove_breakpoint(target, breakpoint);
716 int target_add_watchpoint(struct target *target,
717 struct watchpoint *watchpoint)
719 if (target->state != TARGET_HALTED) {
720 LOG_WARNING("target %s is not halted", target->cmd_name);
721 return ERROR_TARGET_NOT_HALTED;
723 return target->type->add_watchpoint(target, watchpoint);
725 int target_remove_watchpoint(struct target *target,
726 struct watchpoint *watchpoint)
728 return target->type->remove_watchpoint(target, watchpoint);
731 int target_get_gdb_reg_list(struct target *target,
732 struct reg **reg_list[], int *reg_list_size)
734 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
736 int target_step(struct target *target,
737 int current, uint32_t address, int handle_breakpoints)
739 return target->type->step(target, current, address, handle_breakpoints);
744 * Reset the @c examined flag for the given target.
745 * Pure paranoia -- targets are zeroed on allocation.
747 static void target_reset_examined(struct target *target)
749 target->examined = false;
752 static int
753 err_read_phys_memory(struct target *target, uint32_t address,
754 uint32_t size, uint32_t count, uint8_t *buffer)
756 LOG_ERROR("Not implemented: %s", __func__);
757 return ERROR_FAIL;
760 static int
761 err_write_phys_memory(struct target *target, uint32_t address,
762 uint32_t size, uint32_t count, uint8_t *buffer)
764 LOG_ERROR("Not implemented: %s", __func__);
765 return ERROR_FAIL;
768 static int handle_target(void *priv);
770 static int target_init_one(struct command_context *cmd_ctx,
771 struct target *target)
773 target_reset_examined(target);
775 struct target_type *type = target->type;
776 if (type->examine == NULL)
777 type->examine = default_examine;
779 if (type->check_reset== NULL)
780 type->check_reset = default_check_reset;
782 int retval = type->init_target(cmd_ctx, target);
783 if (ERROR_OK != retval)
785 LOG_ERROR("target '%s' init failed", target_name(target));
786 return retval;
790 * @todo get rid of those *memory_imp() methods, now that all
791 * callers are using target_*_memory() accessors ... and make
792 * sure the "physical" paths handle the same issues.
794 /* a non-invasive way(in terms of patches) to add some code that
795 * runs before the type->write/read_memory implementation
797 type->write_memory_imp = target->type->write_memory;
798 type->write_memory = target_write_memory_imp;
800 type->read_memory_imp = target->type->read_memory;
801 type->read_memory = target_read_memory_imp;
803 type->soft_reset_halt_imp = target->type->soft_reset_halt;
804 type->soft_reset_halt = target_soft_reset_halt_imp;
806 /* Sanity-check MMU support ... stub in what we must, to help
807 * implement it in stages, but warn if we need to do so.
809 if (type->mmu)
811 if (type->write_phys_memory == NULL)
813 LOG_ERROR("type '%s' is missing write_phys_memory",
814 type->name);
815 type->write_phys_memory = err_write_phys_memory;
817 if (type->read_phys_memory == NULL)
819 LOG_ERROR("type '%s' is missing read_phys_memory",
820 type->name);
821 type->read_phys_memory = err_read_phys_memory;
823 if (type->virt2phys == NULL)
825 LOG_ERROR("type '%s' is missing virt2phys", type->name);
826 type->virt2phys = identity_virt2phys;
829 else
831 /* Make sure no-MMU targets all behave the same: make no
832 * distinction between physical and virtual addresses, and
833 * ensure that virt2phys() is always an identity mapping.
835 if (type->write_phys_memory || type->read_phys_memory
836 || type->virt2phys)
838 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
841 type->mmu = no_mmu;
842 type->write_phys_memory = type->write_memory;
843 type->read_phys_memory = type->read_memory;
844 type->virt2phys = identity_virt2phys;
846 return ERROR_OK;
849 static int target_init(struct command_context *cmd_ctx)
851 struct target *target;
852 int retval;
854 for (target = all_targets; target; target = target->next)
856 retval = target_init_one(cmd_ctx, target);
857 if (ERROR_OK != retval)
858 return retval;
861 if (!all_targets)
862 return ERROR_OK;
864 retval = target_register_user_commands(cmd_ctx);
865 if (ERROR_OK != retval)
866 return retval;
868 retval = target_register_timer_callback(&handle_target,
869 polling_interval, 1, cmd_ctx->interp);
870 if (ERROR_OK != retval)
871 return retval;
873 return ERROR_OK;
876 COMMAND_HANDLER(handle_target_init_command)
878 if (CMD_ARGC != 0)
879 return ERROR_COMMAND_SYNTAX_ERROR;
881 static bool target_initialized = false;
882 if (target_initialized)
884 LOG_INFO("'target init' has already been called");
885 return ERROR_OK;
887 target_initialized = true;
889 LOG_DEBUG("Initializing targets...");
890 return target_init(CMD_CTX);
893 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
895 struct target_event_callback **callbacks_p = &target_event_callbacks;
897 if (callback == NULL)
899 return ERROR_INVALID_ARGUMENTS;
902 if (*callbacks_p)
904 while ((*callbacks_p)->next)
905 callbacks_p = &((*callbacks_p)->next);
906 callbacks_p = &((*callbacks_p)->next);
909 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
910 (*callbacks_p)->callback = callback;
911 (*callbacks_p)->priv = priv;
912 (*callbacks_p)->next = NULL;
914 return ERROR_OK;
917 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
919 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
920 struct timeval now;
922 if (callback == NULL)
924 return ERROR_INVALID_ARGUMENTS;
927 if (*callbacks_p)
929 while ((*callbacks_p)->next)
930 callbacks_p = &((*callbacks_p)->next);
931 callbacks_p = &((*callbacks_p)->next);
934 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
935 (*callbacks_p)->callback = callback;
936 (*callbacks_p)->periodic = periodic;
937 (*callbacks_p)->time_ms = time_ms;
939 gettimeofday(&now, NULL);
940 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
941 time_ms -= (time_ms % 1000);
942 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
943 if ((*callbacks_p)->when.tv_usec > 1000000)
945 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
946 (*callbacks_p)->when.tv_sec += 1;
949 (*callbacks_p)->priv = priv;
950 (*callbacks_p)->next = NULL;
952 return ERROR_OK;
955 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
957 struct target_event_callback **p = &target_event_callbacks;
958 struct target_event_callback *c = target_event_callbacks;
960 if (callback == NULL)
962 return ERROR_INVALID_ARGUMENTS;
965 while (c)
967 struct target_event_callback *next = c->next;
968 if ((c->callback == callback) && (c->priv == priv))
970 *p = next;
971 free(c);
972 return ERROR_OK;
974 else
975 p = &(c->next);
976 c = next;
979 return ERROR_OK;
982 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
984 struct target_timer_callback **p = &target_timer_callbacks;
985 struct target_timer_callback *c = target_timer_callbacks;
987 if (callback == NULL)
989 return ERROR_INVALID_ARGUMENTS;
992 while (c)
994 struct target_timer_callback *next = c->next;
995 if ((c->callback == callback) && (c->priv == priv))
997 *p = next;
998 free(c);
999 return ERROR_OK;
1001 else
1002 p = &(c->next);
1003 c = next;
1006 return ERROR_OK;
1009 int target_call_event_callbacks(struct target *target, enum target_event event)
1011 struct target_event_callback *callback = target_event_callbacks;
1012 struct target_event_callback *next_callback;
1014 if (event == TARGET_EVENT_HALTED)
1016 /* execute early halted first */
1017 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1020 LOG_DEBUG("target event %i (%s)",
1021 event,
1022 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1024 target_handle_event(target, event);
1026 while (callback)
1028 next_callback = callback->next;
1029 callback->callback(target, event, callback->priv);
1030 callback = next_callback;
1033 return ERROR_OK;
1036 static int target_timer_callback_periodic_restart(
1037 struct target_timer_callback *cb, struct timeval *now)
1039 int time_ms = cb->time_ms;
1040 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1041 time_ms -= (time_ms % 1000);
1042 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1043 if (cb->when.tv_usec > 1000000)
1045 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1046 cb->when.tv_sec += 1;
1048 return ERROR_OK;
1051 static int target_call_timer_callback(struct target_timer_callback *cb,
1052 struct timeval *now)
1054 cb->callback(cb->priv);
1056 if (cb->periodic)
1057 return target_timer_callback_periodic_restart(cb, now);
1059 return target_unregister_timer_callback(cb->callback, cb->priv);
1062 static int target_call_timer_callbacks_check_time(int checktime)
1064 keep_alive();
1066 struct timeval now;
1067 gettimeofday(&now, NULL);
1069 struct target_timer_callback *callback = target_timer_callbacks;
1070 while (callback)
1072 // cleaning up may unregister and free this callback
1073 struct target_timer_callback *next_callback = callback->next;
1075 bool call_it = callback->callback &&
1076 ((!checktime && callback->periodic) ||
1077 now.tv_sec > callback->when.tv_sec ||
1078 (now.tv_sec == callback->when.tv_sec &&
1079 now.tv_usec >= callback->when.tv_usec));
1081 if (call_it)
1083 int retval = target_call_timer_callback(callback, &now);
1084 if (retval != ERROR_OK)
1085 return retval;
1088 callback = next_callback;
1091 return ERROR_OK;
1094 int target_call_timer_callbacks(void)
1096 return target_call_timer_callbacks_check_time(1);
1099 /* invoke periodic callbacks immediately */
1100 int target_call_timer_callbacks_now(void)
1102 return target_call_timer_callbacks_check_time(0);
1105 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1107 struct working_area *c = target->working_areas;
1108 struct working_area *new_wa = NULL;
1110 /* Reevaluate working area address based on MMU state*/
1111 if (target->working_areas == NULL)
1113 int retval;
1114 int enabled;
1116 retval = target->type->mmu(target, &enabled);
1117 if (retval != ERROR_OK)
1119 return retval;
1122 if (!enabled) {
1123 if (target->working_area_phys_spec) {
1124 LOG_DEBUG("MMU disabled, using physical "
1125 "address for working memory 0x%08x",
1126 (unsigned)target->working_area_phys);
1127 target->working_area = target->working_area_phys;
1128 } else {
1129 LOG_ERROR("No working memory available. "
1130 "Specify -work-area-phys to target.");
1131 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1133 } else {
1134 if (target->working_area_virt_spec) {
1135 LOG_DEBUG("MMU enabled, using virtual "
1136 "address for working memory 0x%08x",
1137 (unsigned)target->working_area_virt);
1138 target->working_area = target->working_area_virt;
1139 } else {
1140 LOG_ERROR("No working memory available. "
1141 "Specify -work-area-virt to target.");
1142 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1147 /* only allocate multiples of 4 byte */
1148 if (size % 4)
1150 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1151 size = (size + 3) & (~3);
1154 /* see if there's already a matching working area */
1155 while (c)
1157 if ((c->free) && (c->size == size))
1159 new_wa = c;
1160 break;
1162 c = c->next;
1165 /* if not, allocate a new one */
1166 if (!new_wa)
1168 struct working_area **p = &target->working_areas;
1169 uint32_t first_free = target->working_area;
1170 uint32_t free_size = target->working_area_size;
1172 c = target->working_areas;
1173 while (c)
1175 first_free += c->size;
1176 free_size -= c->size;
1177 p = &c->next;
1178 c = c->next;
1181 if (free_size < size)
1183 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1186 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1188 new_wa = malloc(sizeof(struct working_area));
1189 new_wa->next = NULL;
1190 new_wa->size = size;
1191 new_wa->address = first_free;
1193 if (target->backup_working_area)
1195 int retval;
1196 new_wa->backup = malloc(new_wa->size);
1197 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1199 free(new_wa->backup);
1200 free(new_wa);
1201 return retval;
1204 else
1206 new_wa->backup = NULL;
1209 /* put new entry in list */
1210 *p = new_wa;
1213 /* mark as used, and return the new (reused) area */
1214 new_wa->free = 0;
1215 *area = new_wa;
1217 /* user pointer */
1218 new_wa->user = area;
1220 return ERROR_OK;
1223 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1225 int retval;
1227 retval = target_alloc_working_area_try(target, size, area);
1228 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1230 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1232 return retval;
1236 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1238 if (area->free)
1239 return ERROR_OK;
1241 if (restore && target->backup_working_area)
1243 int retval;
1244 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1245 return retval;
1248 area->free = 1;
1250 /* mark user pointer invalid */
1251 *area->user = NULL;
1252 area->user = NULL;
1254 return ERROR_OK;
1257 int target_free_working_area(struct target *target, struct working_area *area)
1259 return target_free_working_area_restore(target, area, 1);
1262 /* free resources and restore memory, if restoring memory fails,
1263 * free up resources anyway
1265 static void target_free_all_working_areas_restore(struct target *target, int restore)
1267 struct working_area *c = target->working_areas;
1269 while (c)
1271 struct working_area *next = c->next;
1272 target_free_working_area_restore(target, c, restore);
1274 if (c->backup)
1275 free(c->backup);
1277 free(c);
1279 c = next;
1282 target->working_areas = NULL;
1285 void target_free_all_working_areas(struct target *target)
1287 target_free_all_working_areas_restore(target, 1);
1290 int target_arch_state(struct target *target)
1292 int retval;
1293 if (target == NULL)
1295 LOG_USER("No target has been configured");
1296 return ERROR_OK;
1299 LOG_USER("target state: %s", target_state_name( target ));
1301 if (target->state != TARGET_HALTED)
1302 return ERROR_OK;
1304 retval = target->type->arch_state(target);
1305 return retval;
1308 /* Single aligned words are guaranteed to use 16 or 32 bit access
1309 * mode respectively, otherwise data is handled as quickly as
1310 * possible
1312 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1314 int retval;
1315 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1316 (int)size, (unsigned)address);
1318 if (!target_was_examined(target))
1320 LOG_ERROR("Target not examined yet");
1321 return ERROR_FAIL;
1324 if (size == 0) {
1325 return ERROR_OK;
1328 if ((address + size - 1) < address)
1330 /* GDB can request this when e.g. PC is 0xfffffffc*/
1331 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1332 (unsigned)address,
1333 (unsigned)size);
1334 return ERROR_FAIL;
1337 if (((address % 2) == 0) && (size == 2))
1339 return target_write_memory(target, address, 2, 1, buffer);
1342 /* handle unaligned head bytes */
1343 if (address % 4)
1345 uint32_t unaligned = 4 - (address % 4);
1347 if (unaligned > size)
1348 unaligned = size;
1350 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1351 return retval;
1353 buffer += unaligned;
1354 address += unaligned;
1355 size -= unaligned;
1358 /* handle aligned words */
1359 if (size >= 4)
1361 int aligned = size - (size % 4);
1363 /* use bulk writes above a certain limit. This may have to be changed */
1364 if (aligned > 128)
1366 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1367 return retval;
1369 else
1371 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1372 return retval;
1375 buffer += aligned;
1376 address += aligned;
1377 size -= aligned;
1380 /* handle tail writes of less than 4 bytes */
1381 if (size > 0)
1383 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1384 return retval;
1387 return ERROR_OK;
1390 /* Single aligned words are guaranteed to use 16 or 32 bit access
1391 * mode respectively, otherwise data is handled as quickly as
1392 * possible
1394 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1396 int retval;
1397 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1398 (int)size, (unsigned)address);
1400 if (!target_was_examined(target))
1402 LOG_ERROR("Target not examined yet");
1403 return ERROR_FAIL;
1406 if (size == 0) {
1407 return ERROR_OK;
1410 if ((address + size - 1) < address)
1412 /* GDB can request this when e.g. PC is 0xfffffffc*/
1413 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1414 address,
1415 size);
1416 return ERROR_FAIL;
1419 if (((address % 2) == 0) && (size == 2))
1421 return target_read_memory(target, address, 2, 1, buffer);
1424 /* handle unaligned head bytes */
1425 if (address % 4)
1427 uint32_t unaligned = 4 - (address % 4);
1429 if (unaligned > size)
1430 unaligned = size;
1432 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1433 return retval;
1435 buffer += unaligned;
1436 address += unaligned;
1437 size -= unaligned;
1440 /* handle aligned words */
1441 if (size >= 4)
1443 int aligned = size - (size % 4);
1445 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1446 return retval;
1448 buffer += aligned;
1449 address += aligned;
1450 size -= aligned;
1453 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1454 if(size >=2)
1456 int aligned = size - (size%2);
1457 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1458 if (retval != ERROR_OK)
1459 return retval;
1461 buffer += aligned;
1462 address += aligned;
1463 size -= aligned;
1465 /* handle tail writes of less than 4 bytes */
1466 if (size > 0)
1468 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1469 return retval;
1472 return ERROR_OK;
1475 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1477 uint8_t *buffer;
1478 int retval;
1479 uint32_t i;
1480 uint32_t checksum = 0;
1481 if (!target_was_examined(target))
1483 LOG_ERROR("Target not examined yet");
1484 return ERROR_FAIL;
1487 if ((retval = target->type->checksum_memory(target, address,
1488 size, &checksum)) != ERROR_OK)
1490 buffer = malloc(size);
1491 if (buffer == NULL)
1493 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1494 return ERROR_INVALID_ARGUMENTS;
1496 retval = target_read_buffer(target, address, size, buffer);
1497 if (retval != ERROR_OK)
1499 free(buffer);
1500 return retval;
1503 /* convert to target endianess */
1504 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1506 uint32_t target_data;
1507 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1508 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1511 retval = image_calculate_checksum(buffer, size, &checksum);
1512 free(buffer);
1515 *crc = checksum;
1517 return retval;
1520 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1522 int retval;
1523 if (!target_was_examined(target))
1525 LOG_ERROR("Target not examined yet");
1526 return ERROR_FAIL;
1529 if (target->type->blank_check_memory == 0)
1530 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1532 retval = target->type->blank_check_memory(target, address, size, blank);
1534 return retval;
1537 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1539 uint8_t value_buf[4];
1540 if (!target_was_examined(target))
1542 LOG_ERROR("Target not examined yet");
1543 return ERROR_FAIL;
1546 int retval = target_read_memory(target, address, 4, 1, value_buf);
1548 if (retval == ERROR_OK)
1550 *value = target_buffer_get_u32(target, value_buf);
1551 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1552 address,
1553 *value);
1555 else
1557 *value = 0x0;
1558 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1559 address);
1562 return retval;
1565 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1567 uint8_t value_buf[2];
1568 if (!target_was_examined(target))
1570 LOG_ERROR("Target not examined yet");
1571 return ERROR_FAIL;
1574 int retval = target_read_memory(target, address, 2, 1, value_buf);
1576 if (retval == ERROR_OK)
1578 *value = target_buffer_get_u16(target, value_buf);
1579 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1580 address,
1581 *value);
1583 else
1585 *value = 0x0;
1586 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1587 address);
1590 return retval;
1593 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1595 int retval = target_read_memory(target, address, 1, 1, value);
1596 if (!target_was_examined(target))
1598 LOG_ERROR("Target not examined yet");
1599 return ERROR_FAIL;
1602 if (retval == ERROR_OK)
1604 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1605 address,
1606 *value);
1608 else
1610 *value = 0x0;
1611 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1612 address);
1615 return retval;
1618 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1620 int retval;
1621 uint8_t value_buf[4];
1622 if (!target_was_examined(target))
1624 LOG_ERROR("Target not examined yet");
1625 return ERROR_FAIL;
1628 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1629 address,
1630 value);
1632 target_buffer_set_u32(target, value_buf, value);
1633 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1635 LOG_DEBUG("failed: %i", retval);
1638 return retval;
1641 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1643 int retval;
1644 uint8_t value_buf[2];
1645 if (!target_was_examined(target))
1647 LOG_ERROR("Target not examined yet");
1648 return ERROR_FAIL;
1651 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1652 address,
1653 value);
1655 target_buffer_set_u16(target, value_buf, value);
1656 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1658 LOG_DEBUG("failed: %i", retval);
1661 return retval;
1664 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1666 int retval;
1667 if (!target_was_examined(target))
1669 LOG_ERROR("Target not examined yet");
1670 return ERROR_FAIL;
1673 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1674 address, value);
1676 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1678 LOG_DEBUG("failed: %i", retval);
1681 return retval;
1684 COMMAND_HANDLER(handle_targets_command)
1686 struct target *target = all_targets;
1688 if (CMD_ARGC == 1)
1690 target = get_target(CMD_ARGV[0]);
1691 if (target == NULL) {
1692 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1693 goto DumpTargets;
1695 if (!target->tap->enabled) {
1696 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1697 "can't be the current target\n",
1698 target->tap->dotted_name);
1699 return ERROR_FAIL;
1702 CMD_CTX->current_target = target->target_number;
1703 return ERROR_OK;
1705 DumpTargets:
1707 target = all_targets;
1708 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1709 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1710 while (target)
1712 const char *state;
1713 char marker = ' ';
1715 if (target->tap->enabled)
1716 state = target_state_name( target );
1717 else
1718 state = "tap-disabled";
1720 if (CMD_CTX->current_target == target->target_number)
1721 marker = '*';
1723 /* keep columns lined up to match the headers above */
1724 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1725 target->target_number,
1726 marker,
1727 target_name(target),
1728 target_type_name(target),
1729 Jim_Nvp_value2name_simple(nvp_target_endian,
1730 target->endianness)->name,
1731 target->tap->dotted_name,
1732 state);
1733 target = target->next;
1736 return ERROR_OK;
1739 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1741 static int powerDropout;
1742 static int srstAsserted;
1744 static int runPowerRestore;
1745 static int runPowerDropout;
1746 static int runSrstAsserted;
1747 static int runSrstDeasserted;
1749 static int sense_handler(void)
1751 static int prevSrstAsserted = 0;
1752 static int prevPowerdropout = 0;
1754 int retval;
1755 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1756 return retval;
1758 int powerRestored;
1759 powerRestored = prevPowerdropout && !powerDropout;
1760 if (powerRestored)
1762 runPowerRestore = 1;
1765 long long current = timeval_ms();
1766 static long long lastPower = 0;
1767 int waitMore = lastPower + 2000 > current;
1768 if (powerDropout && !waitMore)
1770 runPowerDropout = 1;
1771 lastPower = current;
1774 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1775 return retval;
1777 int srstDeasserted;
1778 srstDeasserted = prevSrstAsserted && !srstAsserted;
1780 static long long lastSrst = 0;
1781 waitMore = lastSrst + 2000 > current;
1782 if (srstDeasserted && !waitMore)
1784 runSrstDeasserted = 1;
1785 lastSrst = current;
1788 if (!prevSrstAsserted && srstAsserted)
1790 runSrstAsserted = 1;
1793 prevSrstAsserted = srstAsserted;
1794 prevPowerdropout = powerDropout;
1796 if (srstDeasserted || powerRestored)
1798 /* Other than logging the event we can't do anything here.
1799 * Issuing a reset is a particularly bad idea as we might
1800 * be inside a reset already.
1804 return ERROR_OK;
1807 static int backoff_times = 0;
1808 static int backoff_count = 0;
1810 /* process target state changes */
1811 static int handle_target(void *priv)
1813 Jim_Interp *interp = (Jim_Interp *)priv;
1814 int retval = ERROR_OK;
1816 if (!is_jtag_poll_safe())
1818 /* polling is disabled currently */
1819 return ERROR_OK;
1822 /* we do not want to recurse here... */
1823 static int recursive = 0;
1824 if (! recursive)
1826 recursive = 1;
1827 sense_handler();
1828 /* danger! running these procedures can trigger srst assertions and power dropouts.
1829 * We need to avoid an infinite loop/recursion here and we do that by
1830 * clearing the flags after running these events.
1832 int did_something = 0;
1833 if (runSrstAsserted)
1835 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1836 Jim_Eval(interp, "srst_asserted");
1837 did_something = 1;
1839 if (runSrstDeasserted)
1841 Jim_Eval(interp, "srst_deasserted");
1842 did_something = 1;
1844 if (runPowerDropout)
1846 LOG_INFO("Power dropout detected, running power_dropout proc.");
1847 Jim_Eval(interp, "power_dropout");
1848 did_something = 1;
1850 if (runPowerRestore)
1852 Jim_Eval(interp, "power_restore");
1853 did_something = 1;
1856 if (did_something)
1858 /* clear detect flags */
1859 sense_handler();
1862 /* clear action flags */
1864 runSrstAsserted = 0;
1865 runSrstDeasserted = 0;
1866 runPowerRestore = 0;
1867 runPowerDropout = 0;
1869 recursive = 0;
1872 if (backoff_times > backoff_count)
1874 /* do not poll this time as we failed previously */
1875 backoff_count++;
1876 return ERROR_OK;
1878 backoff_count = 0;
1880 /* Poll targets for state changes unless that's globally disabled.
1881 * Skip targets that are currently disabled.
1883 for (struct target *target = all_targets;
1884 is_jtag_poll_safe() && target;
1885 target = target->next)
1887 if (!target->tap->enabled)
1888 continue;
1890 /* only poll target if we've got power and srst isn't asserted */
1891 if (!powerDropout && !srstAsserted)
1893 /* polling may fail silently until the target has been examined */
1894 if ((retval = target_poll(target)) != ERROR_OK)
1896 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1897 if (backoff_times * polling_interval < 5000)
1899 backoff_times *= 2;
1900 backoff_times++;
1902 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1904 /* Tell GDB to halt the debugger. This allows the user to
1905 * run monitor commands to handle the situation.
1907 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1908 return retval;
1910 /* Since we succeeded, we reset backoff count */
1911 if (backoff_times > 0)
1913 LOG_USER("Polling succeeded again");
1915 backoff_times = 0;
1919 return retval;
1922 COMMAND_HANDLER(handle_reg_command)
1924 struct target *target;
1925 struct reg *reg = NULL;
1926 unsigned count = 0;
1927 char *value;
1929 LOG_DEBUG("-");
1931 target = get_current_target(CMD_CTX);
1933 /* list all available registers for the current target */
1934 if (CMD_ARGC == 0)
1936 struct reg_cache *cache = target->reg_cache;
1938 count = 0;
1939 while (cache)
1941 unsigned i;
1943 command_print(CMD_CTX, "===== %s", cache->name);
1945 for (i = 0, reg = cache->reg_list;
1946 i < cache->num_regs;
1947 i++, reg++, count++)
1949 /* only print cached values if they are valid */
1950 if (reg->valid) {
1951 value = buf_to_str(reg->value,
1952 reg->size, 16);
1953 command_print(CMD_CTX,
1954 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1955 count, reg->name,
1956 reg->size, value,
1957 reg->dirty
1958 ? " (dirty)"
1959 : "");
1960 free(value);
1961 } else {
1962 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1963 count, reg->name,
1964 reg->size) ;
1967 cache = cache->next;
1970 return ERROR_OK;
1973 /* access a single register by its ordinal number */
1974 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1976 unsigned num;
1977 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1979 struct reg_cache *cache = target->reg_cache;
1980 count = 0;
1981 while (cache)
1983 unsigned i;
1984 for (i = 0; i < cache->num_regs; i++)
1986 if (count++ == num)
1988 reg = &cache->reg_list[i];
1989 break;
1992 if (reg)
1993 break;
1994 cache = cache->next;
1997 if (!reg)
1999 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2000 return ERROR_OK;
2002 } else /* access a single register by its name */
2004 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2006 if (!reg)
2008 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2009 return ERROR_OK;
2013 /* display a register */
2014 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2016 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2017 reg->valid = 0;
2019 if (reg->valid == 0)
2021 reg->type->get(reg);
2023 value = buf_to_str(reg->value, reg->size, 16);
2024 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2025 free(value);
2026 return ERROR_OK;
2029 /* set register value */
2030 if (CMD_ARGC == 2)
2032 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2033 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2035 reg->type->set(reg, buf);
2037 value = buf_to_str(reg->value, reg->size, 16);
2038 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2039 free(value);
2041 free(buf);
2043 return ERROR_OK;
2046 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2048 return ERROR_OK;
2051 COMMAND_HANDLER(handle_poll_command)
2053 int retval = ERROR_OK;
2054 struct target *target = get_current_target(CMD_CTX);
2056 if (CMD_ARGC == 0)
2058 command_print(CMD_CTX, "background polling: %s",
2059 jtag_poll_get_enabled() ? "on" : "off");
2060 command_print(CMD_CTX, "TAP: %s (%s)",
2061 target->tap->dotted_name,
2062 target->tap->enabled ? "enabled" : "disabled");
2063 if (!target->tap->enabled)
2064 return ERROR_OK;
2065 if ((retval = target_poll(target)) != ERROR_OK)
2066 return retval;
2067 if ((retval = target_arch_state(target)) != ERROR_OK)
2068 return retval;
2070 else if (CMD_ARGC == 1)
2072 bool enable;
2073 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2074 jtag_poll_set_enabled(enable);
2076 else
2078 return ERROR_COMMAND_SYNTAX_ERROR;
2081 return retval;
2084 COMMAND_HANDLER(handle_wait_halt_command)
2086 if (CMD_ARGC > 1)
2087 return ERROR_COMMAND_SYNTAX_ERROR;
2089 unsigned ms = 5000;
2090 if (1 == CMD_ARGC)
2092 int retval = parse_uint(CMD_ARGV[0], &ms);
2093 if (ERROR_OK != retval)
2095 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2096 return ERROR_COMMAND_SYNTAX_ERROR;
2098 // convert seconds (given) to milliseconds (needed)
2099 ms *= 1000;
2102 struct target *target = get_current_target(CMD_CTX);
2103 return target_wait_state(target, TARGET_HALTED, ms);
2106 /* wait for target state to change. The trick here is to have a low
2107 * latency for short waits and not to suck up all the CPU time
2108 * on longer waits.
2110 * After 500ms, keep_alive() is invoked
2112 int target_wait_state(struct target *target, enum target_state state, int ms)
2114 int retval;
2115 long long then = 0, cur;
2116 int once = 1;
2118 for (;;)
2120 if ((retval = target_poll(target)) != ERROR_OK)
2121 return retval;
2122 if (target->state == state)
2124 break;
2126 cur = timeval_ms();
2127 if (once)
2129 once = 0;
2130 then = timeval_ms();
2131 LOG_DEBUG("waiting for target %s...",
2132 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2135 if (cur-then > 500)
2137 keep_alive();
2140 if ((cur-then) > ms)
2142 LOG_ERROR("timed out while waiting for target %s",
2143 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2144 return ERROR_FAIL;
2148 return ERROR_OK;
2151 COMMAND_HANDLER(handle_halt_command)
2153 LOG_DEBUG("-");
2155 struct target *target = get_current_target(CMD_CTX);
2156 int retval = target_halt(target);
2157 if (ERROR_OK != retval)
2158 return retval;
2160 if (CMD_ARGC == 1)
2162 unsigned wait_local;
2163 retval = parse_uint(CMD_ARGV[0], &wait_local);
2164 if (ERROR_OK != retval)
2165 return ERROR_COMMAND_SYNTAX_ERROR;
2166 if (!wait_local)
2167 return ERROR_OK;
2170 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2173 COMMAND_HANDLER(handle_soft_reset_halt_command)
2175 struct target *target = get_current_target(CMD_CTX);
2177 LOG_USER("requesting target halt and executing a soft reset");
2179 target->type->soft_reset_halt(target);
2181 return ERROR_OK;
2184 COMMAND_HANDLER(handle_reset_command)
2186 if (CMD_ARGC > 1)
2187 return ERROR_COMMAND_SYNTAX_ERROR;
2189 enum target_reset_mode reset_mode = RESET_RUN;
2190 if (CMD_ARGC == 1)
2192 const Jim_Nvp *n;
2193 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2194 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2195 return ERROR_COMMAND_SYNTAX_ERROR;
2197 reset_mode = n->value;
2200 /* reset *all* targets */
2201 return target_process_reset(CMD_CTX, reset_mode);
2205 COMMAND_HANDLER(handle_resume_command)
2207 int current = 1;
2208 if (CMD_ARGC > 1)
2209 return ERROR_COMMAND_SYNTAX_ERROR;
2211 struct target *target = get_current_target(CMD_CTX);
2212 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2214 /* with no CMD_ARGV, resume from current pc, addr = 0,
2215 * with one arguments, addr = CMD_ARGV[0],
2216 * handle breakpoints, not debugging */
2217 uint32_t addr = 0;
2218 if (CMD_ARGC == 1)
2220 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2221 current = 0;
2224 return target_resume(target, current, addr, 1, 0);
2227 COMMAND_HANDLER(handle_step_command)
2229 if (CMD_ARGC > 1)
2230 return ERROR_COMMAND_SYNTAX_ERROR;
2232 LOG_DEBUG("-");
2234 /* with no CMD_ARGV, step from current pc, addr = 0,
2235 * with one argument addr = CMD_ARGV[0],
2236 * handle breakpoints, debugging */
2237 uint32_t addr = 0;
2238 int current_pc = 1;
2239 if (CMD_ARGC == 1)
2241 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2242 current_pc = 0;
2245 struct target *target = get_current_target(CMD_CTX);
2247 return target->type->step(target, current_pc, addr, 1);
2250 static void handle_md_output(struct command_context *cmd_ctx,
2251 struct target *target, uint32_t address, unsigned size,
2252 unsigned count, const uint8_t *buffer)
2254 const unsigned line_bytecnt = 32;
2255 unsigned line_modulo = line_bytecnt / size;
2257 char output[line_bytecnt * 4 + 1];
2258 unsigned output_len = 0;
2260 const char *value_fmt;
2261 switch (size) {
2262 case 4: value_fmt = "%8.8x "; break;
2263 case 2: value_fmt = "%4.4x "; break;
2264 case 1: value_fmt = "%2.2x "; break;
2265 default:
2266 /* "can't happen", caller checked */
2267 LOG_ERROR("invalid memory read size: %u", size);
2268 return;
2271 for (unsigned i = 0; i < count; i++)
2273 if (i % line_modulo == 0)
2275 output_len += snprintf(output + output_len,
2276 sizeof(output) - output_len,
2277 "0x%8.8x: ",
2278 (unsigned)(address + (i*size)));
2281 uint32_t value = 0;
2282 const uint8_t *value_ptr = buffer + i * size;
2283 switch (size) {
2284 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2285 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2286 case 1: value = *value_ptr;
2288 output_len += snprintf(output + output_len,
2289 sizeof(output) - output_len,
2290 value_fmt, value);
2292 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2294 command_print(cmd_ctx, "%s", output);
2295 output_len = 0;
2300 COMMAND_HANDLER(handle_md_command)
2302 if (CMD_ARGC < 1)
2303 return ERROR_COMMAND_SYNTAX_ERROR;
2305 unsigned size = 0;
2306 switch (CMD_NAME[2]) {
2307 case 'w': size = 4; break;
2308 case 'h': size = 2; break;
2309 case 'b': size = 1; break;
2310 default: return ERROR_COMMAND_SYNTAX_ERROR;
2313 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2314 int (*fn)(struct target *target,
2315 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2316 if (physical)
2318 CMD_ARGC--;
2319 CMD_ARGV++;
2320 fn=target_read_phys_memory;
2321 } else
2323 fn=target_read_memory;
2325 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2327 return ERROR_COMMAND_SYNTAX_ERROR;
2330 uint32_t address;
2331 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2333 unsigned count = 1;
2334 if (CMD_ARGC == 2)
2335 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2337 uint8_t *buffer = calloc(count, size);
2339 struct target *target = get_current_target(CMD_CTX);
2340 int retval = fn(target, address, size, count, buffer);
2341 if (ERROR_OK == retval)
2342 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2344 free(buffer);
2346 return retval;
2349 typedef int (*target_write_fn)(struct target *target,
2350 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2352 static int target_write_memory_fast(struct target *target,
2353 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2355 return target_write_buffer(target, address, size * count, buffer);
2358 static int target_fill_mem(struct target *target,
2359 uint32_t address,
2360 target_write_fn fn,
2361 unsigned data_size,
2362 /* value */
2363 uint32_t b,
2364 /* count */
2365 unsigned c)
2367 /* We have to write in reasonably large chunks to be able
2368 * to fill large memory areas with any sane speed */
2369 const unsigned chunk_size = 16384;
2370 uint8_t *target_buf = malloc(chunk_size * data_size);
2371 if (target_buf == NULL)
2373 LOG_ERROR("Out of memory");
2374 return ERROR_FAIL;
2377 for (unsigned i = 0; i < chunk_size; i ++)
2379 switch (data_size)
2381 case 4:
2382 target_buffer_set_u32(target, target_buf + i*data_size, b);
2383 break;
2384 case 2:
2385 target_buffer_set_u16(target, target_buf + i*data_size, b);
2386 break;
2387 case 1:
2388 target_buffer_set_u8(target, target_buf + i*data_size, b);
2389 break;
2390 default:
2391 exit(-1);
2395 int retval = ERROR_OK;
2397 for (unsigned x = 0; x < c; x += chunk_size)
2399 unsigned current;
2400 current = c - x;
2401 if (current > chunk_size)
2403 current = chunk_size;
2405 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2406 if (retval != ERROR_OK)
2408 break;
2410 /* avoid GDB timeouts */
2411 keep_alive();
2413 free(target_buf);
2415 return retval;
2419 COMMAND_HANDLER(handle_mw_command)
2421 if (CMD_ARGC < 2)
2423 return ERROR_COMMAND_SYNTAX_ERROR;
2425 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2426 target_write_fn fn;
2427 if (physical)
2429 CMD_ARGC--;
2430 CMD_ARGV++;
2431 fn=target_write_phys_memory;
2432 } else
2434 fn = target_write_memory_fast;
2436 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2437 return ERROR_COMMAND_SYNTAX_ERROR;
2439 uint32_t address;
2440 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2442 uint32_t value;
2443 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2445 unsigned count = 1;
2446 if (CMD_ARGC == 3)
2447 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2449 struct target *target = get_current_target(CMD_CTX);
2450 unsigned wordsize;
2451 switch (CMD_NAME[2])
2453 case 'w':
2454 wordsize = 4;
2455 break;
2456 case 'h':
2457 wordsize = 2;
2458 break;
2459 case 'b':
2460 wordsize = 1;
2461 break;
2462 default:
2463 return ERROR_COMMAND_SYNTAX_ERROR;
2466 return target_fill_mem(target, address, fn, wordsize, value, count);
2469 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2470 uint32_t *min_address, uint32_t *max_address)
2472 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2473 return ERROR_COMMAND_SYNTAX_ERROR;
2475 /* a base address isn't always necessary,
2476 * default to 0x0 (i.e. don't relocate) */
2477 if (CMD_ARGC >= 2)
2479 uint32_t addr;
2480 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2481 image->base_address = addr;
2482 image->base_address_set = 1;
2484 else
2485 image->base_address_set = 0;
2487 image->start_address_set = 0;
2489 if (CMD_ARGC >= 4)
2491 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2493 if (CMD_ARGC == 5)
2495 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2496 // use size (given) to find max (required)
2497 *max_address += *min_address;
2500 if (*min_address > *max_address)
2501 return ERROR_COMMAND_SYNTAX_ERROR;
2503 return ERROR_OK;
2506 COMMAND_HANDLER(handle_load_image_command)
2508 uint8_t *buffer;
2509 size_t buf_cnt;
2510 uint32_t image_size;
2511 uint32_t min_address = 0;
2512 uint32_t max_address = 0xffffffff;
2513 int i;
2514 struct image image;
2516 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2517 &image, &min_address, &max_address);
2518 if (ERROR_OK != retval)
2519 return retval;
2521 struct target *target = get_current_target(CMD_CTX);
2523 struct duration bench;
2524 duration_start(&bench);
2526 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2528 return ERROR_OK;
2531 image_size = 0x0;
2532 retval = ERROR_OK;
2533 for (i = 0; i < image.num_sections; i++)
2535 buffer = malloc(image.sections[i].size);
2536 if (buffer == NULL)
2538 command_print(CMD_CTX,
2539 "error allocating buffer for section (%d bytes)",
2540 (int)(image.sections[i].size));
2541 break;
2544 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2546 free(buffer);
2547 break;
2550 uint32_t offset = 0;
2551 uint32_t length = buf_cnt;
2553 /* DANGER!!! beware of unsigned comparision here!!! */
2555 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2556 (image.sections[i].base_address < max_address))
2558 if (image.sections[i].base_address < min_address)
2560 /* clip addresses below */
2561 offset += min_address-image.sections[i].base_address;
2562 length -= offset;
2565 if (image.sections[i].base_address + buf_cnt > max_address)
2567 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2570 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2572 free(buffer);
2573 break;
2575 image_size += length;
2576 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2577 (unsigned int)length,
2578 image.sections[i].base_address + offset);
2581 free(buffer);
2584 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2586 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2587 "in %fs (%0.3f KiB/s)", image_size,
2588 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2591 image_close(&image);
2593 return retval;
2597 COMMAND_HANDLER(handle_dump_image_command)
2599 struct fileio fileio;
2600 uint8_t buffer[560];
2601 int retval, retvaltemp;
2602 uint32_t address, size;
2603 struct duration bench;
2604 struct target *target = get_current_target(CMD_CTX);
2606 if (CMD_ARGC != 3)
2607 return ERROR_COMMAND_SYNTAX_ERROR;
2609 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2610 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2612 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2613 if (retval != ERROR_OK)
2614 return retval;
2616 duration_start(&bench);
2618 retval = ERROR_OK;
2619 while (size > 0)
2621 size_t size_written;
2622 uint32_t this_run_size = (size > 560) ? 560 : size;
2623 retval = target_read_buffer(target, address, this_run_size, buffer);
2624 if (retval != ERROR_OK)
2626 break;
2629 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2630 if (retval != ERROR_OK)
2632 break;
2635 size -= this_run_size;
2636 address += this_run_size;
2639 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2641 int filesize;
2642 retval = fileio_size(&fileio, &filesize);
2643 if (retval != ERROR_OK)
2644 return retval;
2645 command_print(CMD_CTX,
2646 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2647 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2650 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2651 return retvaltemp;
2653 return retval;
2656 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2658 uint8_t *buffer;
2659 size_t buf_cnt;
2660 uint32_t image_size;
2661 int i;
2662 int retval;
2663 uint32_t checksum = 0;
2664 uint32_t mem_checksum = 0;
2666 struct image image;
2668 struct target *target = get_current_target(CMD_CTX);
2670 if (CMD_ARGC < 1)
2672 return ERROR_COMMAND_SYNTAX_ERROR;
2675 if (!target)
2677 LOG_ERROR("no target selected");
2678 return ERROR_FAIL;
2681 struct duration bench;
2682 duration_start(&bench);
2684 if (CMD_ARGC >= 2)
2686 uint32_t addr;
2687 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2688 image.base_address = addr;
2689 image.base_address_set = 1;
2691 else
2693 image.base_address_set = 0;
2694 image.base_address = 0x0;
2697 image.start_address_set = 0;
2699 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2701 return retval;
2704 image_size = 0x0;
2705 int diffs = 0;
2706 retval = ERROR_OK;
2707 for (i = 0; i < image.num_sections; i++)
2709 buffer = malloc(image.sections[i].size);
2710 if (buffer == NULL)
2712 command_print(CMD_CTX,
2713 "error allocating buffer for section (%d bytes)",
2714 (int)(image.sections[i].size));
2715 break;
2717 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2719 free(buffer);
2720 break;
2723 if (verify)
2725 /* calculate checksum of image */
2726 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2727 if (retval != ERROR_OK)
2729 free(buffer);
2730 break;
2733 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2734 if (retval != ERROR_OK)
2736 free(buffer);
2737 break;
2740 if (checksum != mem_checksum)
2742 /* failed crc checksum, fall back to a binary compare */
2743 uint8_t *data;
2745 if (diffs == 0)
2747 LOG_ERROR("checksum mismatch - attempting binary compare");
2750 data = (uint8_t*)malloc(buf_cnt);
2752 /* Can we use 32bit word accesses? */
2753 int size = 1;
2754 int count = buf_cnt;
2755 if ((count % 4) == 0)
2757 size *= 4;
2758 count /= 4;
2760 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2761 if (retval == ERROR_OK)
2763 uint32_t t;
2764 for (t = 0; t < buf_cnt; t++)
2766 if (data[t] != buffer[t])
2768 command_print(CMD_CTX,
2769 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2770 diffs,
2771 (unsigned)(t + image.sections[i].base_address),
2772 data[t],
2773 buffer[t]);
2774 if (diffs++ >= 127)
2776 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2777 free(data);
2778 free(buffer);
2779 goto done;
2782 keep_alive();
2785 free(data);
2787 } else
2789 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2790 image.sections[i].base_address,
2791 buf_cnt);
2794 free(buffer);
2795 image_size += buf_cnt;
2797 if (diffs > 0)
2799 command_print(CMD_CTX, "No more differences found.");
2801 done:
2802 if (diffs > 0)
2804 retval = ERROR_FAIL;
2806 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2808 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2809 "in %fs (%0.3f KiB/s)", image_size,
2810 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2813 image_close(&image);
2815 return retval;
2818 COMMAND_HANDLER(handle_verify_image_command)
2820 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2823 COMMAND_HANDLER(handle_test_image_command)
2825 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2828 static int handle_bp_command_list(struct command_context *cmd_ctx)
2830 struct target *target = get_current_target(cmd_ctx);
2831 struct breakpoint *breakpoint = target->breakpoints;
2832 while (breakpoint)
2834 if (breakpoint->type == BKPT_SOFT)
2836 char* buf = buf_to_str(breakpoint->orig_instr,
2837 breakpoint->length, 16);
2838 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2839 breakpoint->address,
2840 breakpoint->length,
2841 breakpoint->set, buf);
2842 free(buf);
2844 else
2846 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2847 breakpoint->address,
2848 breakpoint->length, breakpoint->set);
2851 breakpoint = breakpoint->next;
2853 return ERROR_OK;
2856 static int handle_bp_command_set(struct command_context *cmd_ctx,
2857 uint32_t addr, uint32_t length, int hw)
2859 struct target *target = get_current_target(cmd_ctx);
2860 int retval = breakpoint_add(target, addr, length, hw);
2861 if (ERROR_OK == retval)
2862 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2863 else
2864 LOG_ERROR("Failure setting breakpoint");
2865 return retval;
2868 COMMAND_HANDLER(handle_bp_command)
2870 if (CMD_ARGC == 0)
2871 return handle_bp_command_list(CMD_CTX);
2873 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2875 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2876 return ERROR_COMMAND_SYNTAX_ERROR;
2879 uint32_t addr;
2880 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2881 uint32_t length;
2882 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2884 int hw = BKPT_SOFT;
2885 if (CMD_ARGC == 3)
2887 if (strcmp(CMD_ARGV[2], "hw") == 0)
2888 hw = BKPT_HARD;
2889 else
2890 return ERROR_COMMAND_SYNTAX_ERROR;
2893 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2896 COMMAND_HANDLER(handle_rbp_command)
2898 if (CMD_ARGC != 1)
2899 return ERROR_COMMAND_SYNTAX_ERROR;
2901 uint32_t addr;
2902 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2904 struct target *target = get_current_target(CMD_CTX);
2905 breakpoint_remove(target, addr);
2907 return ERROR_OK;
2910 COMMAND_HANDLER(handle_wp_command)
2912 struct target *target = get_current_target(CMD_CTX);
2914 if (CMD_ARGC == 0)
2916 struct watchpoint *watchpoint = target->watchpoints;
2918 while (watchpoint)
2920 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2921 ", len: 0x%8.8" PRIx32
2922 ", r/w/a: %i, value: 0x%8.8" PRIx32
2923 ", mask: 0x%8.8" PRIx32,
2924 watchpoint->address,
2925 watchpoint->length,
2926 (int)watchpoint->rw,
2927 watchpoint->value,
2928 watchpoint->mask);
2929 watchpoint = watchpoint->next;
2931 return ERROR_OK;
2934 enum watchpoint_rw type = WPT_ACCESS;
2935 uint32_t addr = 0;
2936 uint32_t length = 0;
2937 uint32_t data_value = 0x0;
2938 uint32_t data_mask = 0xffffffff;
2940 switch (CMD_ARGC)
2942 case 5:
2943 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2944 // fall through
2945 case 4:
2946 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2947 // fall through
2948 case 3:
2949 switch (CMD_ARGV[2][0])
2951 case 'r':
2952 type = WPT_READ;
2953 break;
2954 case 'w':
2955 type = WPT_WRITE;
2956 break;
2957 case 'a':
2958 type = WPT_ACCESS;
2959 break;
2960 default:
2961 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2962 return ERROR_COMMAND_SYNTAX_ERROR;
2964 // fall through
2965 case 2:
2966 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2967 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2968 break;
2970 default:
2971 command_print(CMD_CTX, "usage: wp [address length "
2972 "[(r|w|a) [value [mask]]]]");
2973 return ERROR_COMMAND_SYNTAX_ERROR;
2976 int retval = watchpoint_add(target, addr, length, type,
2977 data_value, data_mask);
2978 if (ERROR_OK != retval)
2979 LOG_ERROR("Failure setting watchpoints");
2981 return retval;
2984 COMMAND_HANDLER(handle_rwp_command)
2986 if (CMD_ARGC != 1)
2987 return ERROR_COMMAND_SYNTAX_ERROR;
2989 uint32_t addr;
2990 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2992 struct target *target = get_current_target(CMD_CTX);
2993 watchpoint_remove(target, addr);
2995 return ERROR_OK;
3000 * Translate a virtual address to a physical address.
3002 * The low-level target implementation must have logged a detailed error
3003 * which is forwarded to telnet/GDB session.
3005 COMMAND_HANDLER(handle_virt2phys_command)
3007 if (CMD_ARGC != 1)
3008 return ERROR_COMMAND_SYNTAX_ERROR;
3010 uint32_t va;
3011 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3012 uint32_t pa;
3014 struct target *target = get_current_target(CMD_CTX);
3015 int retval = target->type->virt2phys(target, va, &pa);
3016 if (retval == ERROR_OK)
3017 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3019 return retval;
3022 static void writeData(FILE *f, const void *data, size_t len)
3024 size_t written = fwrite(data, 1, len, f);
3025 if (written != len)
3026 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3029 static void writeLong(FILE *f, int l)
3031 int i;
3032 for (i = 0; i < 4; i++)
3034 char c = (l >> (i*8))&0xff;
3035 writeData(f, &c, 1);
3040 static void writeString(FILE *f, char *s)
3042 writeData(f, s, strlen(s));
3045 /* Dump a gmon.out histogram file. */
3046 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3048 uint32_t i;
3049 FILE *f = fopen(filename, "w");
3050 if (f == NULL)
3051 return;
3052 writeString(f, "gmon");
3053 writeLong(f, 0x00000001); /* Version */
3054 writeLong(f, 0); /* padding */
3055 writeLong(f, 0); /* padding */
3056 writeLong(f, 0); /* padding */
3058 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3059 writeData(f, &zero, 1);
3061 /* figure out bucket size */
3062 uint32_t min = samples[0];
3063 uint32_t max = samples[0];
3064 for (i = 0; i < sampleNum; i++)
3066 if (min > samples[i])
3068 min = samples[i];
3070 if (max < samples[i])
3072 max = samples[i];
3076 int addressSpace = (max-min + 1);
3078 static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
3079 uint32_t length = addressSpace;
3080 if (length > maxBuckets)
3082 length = maxBuckets;
3084 int *buckets = malloc(sizeof(int)*length);
3085 if (buckets == NULL)
3087 fclose(f);
3088 return;
3090 memset(buckets, 0, sizeof(int)*length);
3091 for (i = 0; i < sampleNum;i++)
3093 uint32_t address = samples[i];
3094 long long a = address-min;
3095 long long b = length-1;
3096 long long c = addressSpace-1;
3097 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3098 buckets[index_t]++;
3101 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3102 writeLong(f, min); /* low_pc */
3103 writeLong(f, max); /* high_pc */
3104 writeLong(f, length); /* # of samples */
3105 writeLong(f, 64000000); /* 64MHz */
3106 writeString(f, "seconds");
3107 for (i = 0; i < (15-strlen("seconds")); i++)
3108 writeData(f, &zero, 1);
3109 writeString(f, "s");
3111 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3113 char *data = malloc(2*length);
3114 if (data != NULL)
3116 for (i = 0; i < length;i++)
3118 int val;
3119 val = buckets[i];
3120 if (val > 65535)
3122 val = 65535;
3124 data[i*2]=val&0xff;
3125 data[i*2 + 1]=(val >> 8)&0xff;
3127 free(buckets);
3128 writeData(f, data, length * 2);
3129 free(data);
3130 } else
3132 free(buckets);
3135 fclose(f);
3138 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3139 * which will be used as a random sampling of PC */
3140 COMMAND_HANDLER(handle_profile_command)
3142 struct target *target = get_current_target(CMD_CTX);
3143 struct timeval timeout, now;
3145 gettimeofday(&timeout, NULL);
3146 if (CMD_ARGC != 2)
3148 return ERROR_COMMAND_SYNTAX_ERROR;
3150 unsigned offset;
3151 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3153 timeval_add_time(&timeout, offset, 0);
3156 * @todo: Some cores let us sample the PC without the
3157 * annoying halt/resume step; for example, ARMv7 PCSR.
3158 * Provide a way to use that more efficient mechanism.
3161 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3163 static const int maxSample = 10000;
3164 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3165 if (samples == NULL)
3166 return ERROR_OK;
3168 int numSamples = 0;
3169 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3170 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3172 for (;;)
3174 int retval;
3175 target_poll(target);
3176 if (target->state == TARGET_HALTED)
3178 uint32_t t=*((uint32_t *)reg->value);
3179 samples[numSamples++]=t;
3180 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3181 target_poll(target);
3182 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3183 } else if (target->state == TARGET_RUNNING)
3185 /* We want to quickly sample the PC. */
3186 if ((retval = target_halt(target)) != ERROR_OK)
3188 free(samples);
3189 return retval;
3191 } else
3193 command_print(CMD_CTX, "Target not halted or running");
3194 retval = ERROR_OK;
3195 break;
3197 if (retval != ERROR_OK)
3199 break;
3202 gettimeofday(&now, NULL);
3203 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3205 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3206 if ((retval = target_poll(target)) != ERROR_OK)
3208 free(samples);
3209 return retval;
3211 if (target->state == TARGET_HALTED)
3213 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3215 if ((retval = target_poll(target)) != ERROR_OK)
3217 free(samples);
3218 return retval;
3220 writeGmon(samples, numSamples, CMD_ARGV[1]);
3221 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3222 break;
3225 free(samples);
3227 return ERROR_OK;
3230 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3232 char *namebuf;
3233 Jim_Obj *nameObjPtr, *valObjPtr;
3234 int result;
3236 namebuf = alloc_printf("%s(%d)", varname, idx);
3237 if (!namebuf)
3238 return JIM_ERR;
3240 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3241 valObjPtr = Jim_NewIntObj(interp, val);
3242 if (!nameObjPtr || !valObjPtr)
3244 free(namebuf);
3245 return JIM_ERR;
3248 Jim_IncrRefCount(nameObjPtr);
3249 Jim_IncrRefCount(valObjPtr);
3250 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3251 Jim_DecrRefCount(interp, nameObjPtr);
3252 Jim_DecrRefCount(interp, valObjPtr);
3253 free(namebuf);
3254 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3255 return result;
3258 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3260 struct command_context *context;
3261 struct target *target;
3263 context = current_command_context(interp);
3264 assert (context != NULL);
3266 target = get_current_target(context);
3267 if (target == NULL)
3269 LOG_ERROR("mem2array: no current target");
3270 return JIM_ERR;
3273 return target_mem2array(interp, target, argc-1, argv + 1);
3276 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3278 long l;
3279 uint32_t width;
3280 int len;
3281 uint32_t addr;
3282 uint32_t count;
3283 uint32_t v;
3284 const char *varname;
3285 int n, e, retval;
3286 uint32_t i;
3288 /* argv[1] = name of array to receive the data
3289 * argv[2] = desired width
3290 * argv[3] = memory address
3291 * argv[4] = count of times to read
3293 if (argc != 4) {
3294 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3295 return JIM_ERR;
3297 varname = Jim_GetString(argv[0], &len);
3298 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3300 e = Jim_GetLong(interp, argv[1], &l);
3301 width = l;
3302 if (e != JIM_OK) {
3303 return e;
3306 e = Jim_GetLong(interp, argv[2], &l);
3307 addr = l;
3308 if (e != JIM_OK) {
3309 return e;
3311 e = Jim_GetLong(interp, argv[3], &l);
3312 len = l;
3313 if (e != JIM_OK) {
3314 return e;
3316 switch (width) {
3317 case 8:
3318 width = 1;
3319 break;
3320 case 16:
3321 width = 2;
3322 break;
3323 case 32:
3324 width = 4;
3325 break;
3326 default:
3327 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3328 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3329 return JIM_ERR;
3331 if (len == 0) {
3332 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3333 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3334 return JIM_ERR;
3336 if ((addr + (len * width)) < addr) {
3337 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3338 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3339 return JIM_ERR;
3341 /* absurd transfer size? */
3342 if (len > 65536) {
3343 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3344 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3345 return JIM_ERR;
3348 if ((width == 1) ||
3349 ((width == 2) && ((addr & 1) == 0)) ||
3350 ((width == 4) && ((addr & 3) == 0))) {
3351 /* all is well */
3352 } else {
3353 char buf[100];
3354 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3355 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3356 addr,
3357 width);
3358 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3359 return JIM_ERR;
3362 /* Transfer loop */
3364 /* index counter */
3365 n = 0;
3367 size_t buffersize = 4096;
3368 uint8_t *buffer = malloc(buffersize);
3369 if (buffer == NULL)
3370 return JIM_ERR;
3372 /* assume ok */
3373 e = JIM_OK;
3374 while (len) {
3375 /* Slurp... in buffer size chunks */
3377 count = len; /* in objects.. */
3378 if (count > (buffersize/width)) {
3379 count = (buffersize/width);
3382 retval = target_read_memory(target, addr, width, count, buffer);
3383 if (retval != ERROR_OK) {
3384 /* BOO !*/
3385 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3386 (unsigned int)addr,
3387 (int)width,
3388 (int)count);
3389 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3390 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3391 e = JIM_ERR;
3392 len = 0;
3393 } else {
3394 v = 0; /* shut up gcc */
3395 for (i = 0 ;i < count ;i++, n++) {
3396 switch (width) {
3397 case 4:
3398 v = target_buffer_get_u32(target, &buffer[i*width]);
3399 break;
3400 case 2:
3401 v = target_buffer_get_u16(target, &buffer[i*width]);
3402 break;
3403 case 1:
3404 v = buffer[i] & 0x0ff;
3405 break;
3407 new_int_array_element(interp, varname, n, v);
3409 len -= count;
3413 free(buffer);
3415 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3417 return JIM_OK;
3420 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3422 char *namebuf;
3423 Jim_Obj *nameObjPtr, *valObjPtr;
3424 int result;
3425 long l;
3427 namebuf = alloc_printf("%s(%d)", varname, idx);
3428 if (!namebuf)
3429 return JIM_ERR;
3431 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3432 if (!nameObjPtr)
3434 free(namebuf);
3435 return JIM_ERR;
3438 Jim_IncrRefCount(nameObjPtr);
3439 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3440 Jim_DecrRefCount(interp, nameObjPtr);
3441 free(namebuf);
3442 if (valObjPtr == NULL)
3443 return JIM_ERR;
3445 result = Jim_GetLong(interp, valObjPtr, &l);
3446 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3447 *val = l;
3448 return result;
3451 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3453 struct command_context *context;
3454 struct target *target;
3456 context = current_command_context(interp);
3457 assert (context != NULL);
3459 target = get_current_target(context);
3460 if (target == NULL) {
3461 LOG_ERROR("array2mem: no current target");
3462 return JIM_ERR;
3465 return target_array2mem(interp,target, argc-1, argv + 1);
3468 static int target_array2mem(Jim_Interp *interp, struct target *target,
3469 int argc, Jim_Obj *const *argv)
3471 long l;
3472 uint32_t width;
3473 int len;
3474 uint32_t addr;
3475 uint32_t count;
3476 uint32_t v;
3477 const char *varname;
3478 int n, e, retval;
3479 uint32_t i;
3481 /* argv[1] = name of array to get the data
3482 * argv[2] = desired width
3483 * argv[3] = memory address
3484 * argv[4] = count to write
3486 if (argc != 4) {
3487 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3488 return JIM_ERR;
3490 varname = Jim_GetString(argv[0], &len);
3491 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3493 e = Jim_GetLong(interp, argv[1], &l);
3494 width = l;
3495 if (e != JIM_OK) {
3496 return e;
3499 e = Jim_GetLong(interp, argv[2], &l);
3500 addr = l;
3501 if (e != JIM_OK) {
3502 return e;
3504 e = Jim_GetLong(interp, argv[3], &l);
3505 len = l;
3506 if (e != JIM_OK) {
3507 return e;
3509 switch (width) {
3510 case 8:
3511 width = 1;
3512 break;
3513 case 16:
3514 width = 2;
3515 break;
3516 case 32:
3517 width = 4;
3518 break;
3519 default:
3520 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3521 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3522 return JIM_ERR;
3524 if (len == 0) {
3525 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3526 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3527 return JIM_ERR;
3529 if ((addr + (len * width)) < addr) {
3530 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3531 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3532 return JIM_ERR;
3534 /* absurd transfer size? */
3535 if (len > 65536) {
3536 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3537 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3538 return JIM_ERR;
3541 if ((width == 1) ||
3542 ((width == 2) && ((addr & 1) == 0)) ||
3543 ((width == 4) && ((addr & 3) == 0))) {
3544 /* all is well */
3545 } else {
3546 char buf[100];
3547 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3548 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3549 (unsigned int)addr,
3550 (int)width);
3551 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3552 return JIM_ERR;
3555 /* Transfer loop */
3557 /* index counter */
3558 n = 0;
3559 /* assume ok */
3560 e = JIM_OK;
3562 size_t buffersize = 4096;
3563 uint8_t *buffer = malloc(buffersize);
3564 if (buffer == NULL)
3565 return JIM_ERR;
3567 while (len) {
3568 /* Slurp... in buffer size chunks */
3570 count = len; /* in objects.. */
3571 if (count > (buffersize/width)) {
3572 count = (buffersize/width);
3575 v = 0; /* shut up gcc */
3576 for (i = 0 ;i < count ;i++, n++) {
3577 get_int_array_element(interp, varname, n, &v);
3578 switch (width) {
3579 case 4:
3580 target_buffer_set_u32(target, &buffer[i*width], v);
3581 break;
3582 case 2:
3583 target_buffer_set_u16(target, &buffer[i*width], v);
3584 break;
3585 case 1:
3586 buffer[i] = v & 0x0ff;
3587 break;
3590 len -= count;
3592 retval = target_write_memory(target, addr, width, count, buffer);
3593 if (retval != ERROR_OK) {
3594 /* BOO !*/
3595 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3596 (unsigned int)addr,
3597 (int)width,
3598 (int)count);
3599 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3600 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3601 e = JIM_ERR;
3602 len = 0;
3606 free(buffer);
3608 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3610 return JIM_OK;
3613 /* FIX? should we propagate errors here rather than printing them
3614 * and continuing?
3616 void target_handle_event(struct target *target, enum target_event e)
3618 struct target_event_action *teap;
3620 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3621 if (teap->event == e) {
3622 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3623 target->target_number,
3624 target_name(target),
3625 target_type_name(target),
3627 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3628 Jim_GetString(teap->body, NULL));
3629 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3631 Jim_MakeErrorMessage(teap->interp);
3632 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3639 * Returns true only if the target has a handler for the specified event.
3641 bool target_has_event_action(struct target *target, enum target_event event)
3643 struct target_event_action *teap;
3645 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3646 if (teap->event == event)
3647 return true;
3649 return false;
3652 enum target_cfg_param {
3653 TCFG_TYPE,
3654 TCFG_EVENT,
3655 TCFG_WORK_AREA_VIRT,
3656 TCFG_WORK_AREA_PHYS,
3657 TCFG_WORK_AREA_SIZE,
3658 TCFG_WORK_AREA_BACKUP,
3659 TCFG_ENDIAN,
3660 TCFG_VARIANT,
3661 TCFG_CHAIN_POSITION,
3664 static Jim_Nvp nvp_config_opts[] = {
3665 { .name = "-type", .value = TCFG_TYPE },
3666 { .name = "-event", .value = TCFG_EVENT },
3667 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3668 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3669 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3670 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3671 { .name = "-endian" , .value = TCFG_ENDIAN },
3672 { .name = "-variant", .value = TCFG_VARIANT },
3673 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3675 { .name = NULL, .value = -1 }
3678 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3680 Jim_Nvp *n;
3681 Jim_Obj *o;
3682 jim_wide w;
3683 char *cp;
3684 int e;
3686 /* parse config or cget options ... */
3687 while (goi->argc > 0) {
3688 Jim_SetEmptyResult(goi->interp);
3689 /* Jim_GetOpt_Debug(goi); */
3691 if (target->type->target_jim_configure) {
3692 /* target defines a configure function */
3693 /* target gets first dibs on parameters */
3694 e = (*(target->type->target_jim_configure))(target, goi);
3695 if (e == JIM_OK) {
3696 /* more? */
3697 continue;
3699 if (e == JIM_ERR) {
3700 /* An error */
3701 return e;
3703 /* otherwise we 'continue' below */
3705 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3706 if (e != JIM_OK) {
3707 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3708 return e;
3710 switch (n->value) {
3711 case TCFG_TYPE:
3712 /* not setable */
3713 if (goi->isconfigure) {
3714 Jim_SetResultFormatted(goi->interp,
3715 "not settable: %s", n->name);
3716 return JIM_ERR;
3717 } else {
3718 no_params:
3719 if (goi->argc != 0) {
3720 Jim_WrongNumArgs(goi->interp,
3721 goi->argc, goi->argv,
3722 "NO PARAMS");
3723 return JIM_ERR;
3726 Jim_SetResultString(goi->interp,
3727 target_type_name(target), -1);
3728 /* loop for more */
3729 break;
3730 case TCFG_EVENT:
3731 if (goi->argc == 0) {
3732 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3733 return JIM_ERR;
3736 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3737 if (e != JIM_OK) {
3738 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3739 return e;
3742 if (goi->isconfigure) {
3743 if (goi->argc != 1) {
3744 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3745 return JIM_ERR;
3747 } else {
3748 if (goi->argc != 0) {
3749 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3750 return JIM_ERR;
3755 struct target_event_action *teap;
3757 teap = target->event_action;
3758 /* replace existing? */
3759 while (teap) {
3760 if (teap->event == (enum target_event)n->value) {
3761 break;
3763 teap = teap->next;
3766 if (goi->isconfigure) {
3767 bool replace = true;
3768 if (teap == NULL) {
3769 /* create new */
3770 teap = calloc(1, sizeof(*teap));
3771 replace = false;
3773 teap->event = n->value;
3774 teap->interp = goi->interp;
3775 Jim_GetOpt_Obj(goi, &o);
3776 if (teap->body) {
3777 Jim_DecrRefCount(teap->interp, teap->body);
3779 teap->body = Jim_DuplicateObj(goi->interp, o);
3781 * FIXME:
3782 * Tcl/TK - "tk events" have a nice feature.
3783 * See the "BIND" command.
3784 * We should support that here.
3785 * You can specify %X and %Y in the event code.
3786 * The idea is: %T - target name.
3787 * The idea is: %N - target number
3788 * The idea is: %E - event name.
3790 Jim_IncrRefCount(teap->body);
3792 if (!replace)
3794 /* add to head of event list */
3795 teap->next = target->event_action;
3796 target->event_action = teap;
3798 Jim_SetEmptyResult(goi->interp);
3799 } else {
3800 /* get */
3801 if (teap == NULL) {
3802 Jim_SetEmptyResult(goi->interp);
3803 } else {
3804 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3808 /* loop for more */
3809 break;
3811 case TCFG_WORK_AREA_VIRT:
3812 if (goi->isconfigure) {
3813 target_free_all_working_areas(target);
3814 e = Jim_GetOpt_Wide(goi, &w);
3815 if (e != JIM_OK) {
3816 return e;
3818 target->working_area_virt = w;
3819 target->working_area_virt_spec = true;
3820 } else {
3821 if (goi->argc != 0) {
3822 goto no_params;
3825 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3826 /* loop for more */
3827 break;
3829 case TCFG_WORK_AREA_PHYS:
3830 if (goi->isconfigure) {
3831 target_free_all_working_areas(target);
3832 e = Jim_GetOpt_Wide(goi, &w);
3833 if (e != JIM_OK) {
3834 return e;
3836 target->working_area_phys = w;
3837 target->working_area_phys_spec = true;
3838 } else {
3839 if (goi->argc != 0) {
3840 goto no_params;
3843 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3844 /* loop for more */
3845 break;
3847 case TCFG_WORK_AREA_SIZE:
3848 if (goi->isconfigure) {
3849 target_free_all_working_areas(target);
3850 e = Jim_GetOpt_Wide(goi, &w);
3851 if (e != JIM_OK) {
3852 return e;
3854 target->working_area_size = w;
3855 } else {
3856 if (goi->argc != 0) {
3857 goto no_params;
3860 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3861 /* loop for more */
3862 break;
3864 case TCFG_WORK_AREA_BACKUP:
3865 if (goi->isconfigure) {
3866 target_free_all_working_areas(target);
3867 e = Jim_GetOpt_Wide(goi, &w);
3868 if (e != JIM_OK) {
3869 return e;
3871 /* make this exactly 1 or 0 */
3872 target->backup_working_area = (!!w);
3873 } else {
3874 if (goi->argc != 0) {
3875 goto no_params;
3878 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3879 /* loop for more e*/
3880 break;
3882 case TCFG_ENDIAN:
3883 if (goi->isconfigure) {
3884 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3885 if (e != JIM_OK) {
3886 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3887 return e;
3889 target->endianness = n->value;
3890 } else {
3891 if (goi->argc != 0) {
3892 goto no_params;
3895 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3896 if (n->name == NULL) {
3897 target->endianness = TARGET_LITTLE_ENDIAN;
3898 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3900 Jim_SetResultString(goi->interp, n->name, -1);
3901 /* loop for more */
3902 break;
3904 case TCFG_VARIANT:
3905 if (goi->isconfigure) {
3906 if (goi->argc < 1) {
3907 Jim_SetResultFormatted(goi->interp,
3908 "%s ?STRING?",
3909 n->name);
3910 return JIM_ERR;
3912 if (target->variant) {
3913 free((void *)(target->variant));
3915 e = Jim_GetOpt_String(goi, &cp, NULL);
3916 target->variant = strdup(cp);
3917 } else {
3918 if (goi->argc != 0) {
3919 goto no_params;
3922 Jim_SetResultString(goi->interp, target->variant,-1);
3923 /* loop for more */
3924 break;
3925 case TCFG_CHAIN_POSITION:
3926 if (goi->isconfigure) {
3927 Jim_Obj *o_t;
3928 struct jtag_tap *tap;
3929 target_free_all_working_areas(target);
3930 e = Jim_GetOpt_Obj(goi, &o_t);
3931 if (e != JIM_OK) {
3932 return e;
3934 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
3935 if (tap == NULL) {
3936 return JIM_ERR;
3938 /* make this exactly 1 or 0 */
3939 target->tap = tap;
3940 } else {
3941 if (goi->argc != 0) {
3942 goto no_params;
3945 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
3946 /* loop for more e*/
3947 break;
3949 } /* while (goi->argc) */
3952 /* done - we return */
3953 return JIM_OK;
3956 static int
3957 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3959 Jim_GetOptInfo goi;
3961 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3962 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
3963 int need_args = 1 + goi.isconfigure;
3964 if (goi.argc < need_args)
3966 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
3967 goi.isconfigure
3968 ? "missing: -option VALUE ..."
3969 : "missing: -option ...");
3970 return JIM_ERR;
3972 struct target *target = Jim_CmdPrivData(goi.interp);
3973 return target_configure(&goi, target);
3976 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3978 const char *cmd_name = Jim_GetString(argv[0], NULL);
3980 Jim_GetOptInfo goi;
3981 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3983 if (goi.argc < 2 || goi.argc > 4)
3985 Jim_SetResultFormatted(goi.interp,
3986 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
3987 return JIM_ERR;
3990 target_write_fn fn;
3991 fn = target_write_memory_fast;
3993 int e;
3994 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
3996 /* consume it */
3997 struct Jim_Obj *obj;
3998 e = Jim_GetOpt_Obj(&goi, &obj);
3999 if (e != JIM_OK)
4000 return e;
4002 fn = target_write_phys_memory;
4005 jim_wide a;
4006 e = Jim_GetOpt_Wide(&goi, &a);
4007 if (e != JIM_OK)
4008 return e;
4010 jim_wide b;
4011 e = Jim_GetOpt_Wide(&goi, &b);
4012 if (e != JIM_OK)
4013 return e;
4015 jim_wide c = 1;
4016 if (goi.argc == 1)
4018 e = Jim_GetOpt_Wide(&goi, &c);
4019 if (e != JIM_OK)
4020 return e;
4023 /* all args must be consumed */
4024 if (goi.argc != 0)
4026 return JIM_ERR;
4029 struct target *target = Jim_CmdPrivData(goi.interp);
4030 unsigned data_size;
4031 if (strcasecmp(cmd_name, "mww") == 0) {
4032 data_size = 4;
4034 else if (strcasecmp(cmd_name, "mwh") == 0) {
4035 data_size = 2;
4037 else if (strcasecmp(cmd_name, "mwb") == 0) {
4038 data_size = 1;
4039 } else {
4040 LOG_ERROR("command '%s' unknown: ", cmd_name);
4041 return JIM_ERR;
4044 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4047 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4049 const char *cmd_name = Jim_GetString(argv[0], NULL);
4051 Jim_GetOptInfo goi;
4052 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4054 if ((goi.argc < 1) || (goi.argc > 3))
4056 Jim_SetResultFormatted(goi.interp,
4057 "usage: %s [phys] <address> [<count>]", cmd_name);
4058 return JIM_ERR;
4061 int (*fn)(struct target *target,
4062 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4063 fn=target_read_memory;
4065 int e;
4066 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4068 /* consume it */
4069 struct Jim_Obj *obj;
4070 e = Jim_GetOpt_Obj(&goi, &obj);
4071 if (e != JIM_OK)
4072 return e;
4074 fn=target_read_phys_memory;
4077 jim_wide a;
4078 e = Jim_GetOpt_Wide(&goi, &a);
4079 if (e != JIM_OK) {
4080 return JIM_ERR;
4082 jim_wide c;
4083 if (goi.argc == 1) {
4084 e = Jim_GetOpt_Wide(&goi, &c);
4085 if (e != JIM_OK) {
4086 return JIM_ERR;
4088 } else {
4089 c = 1;
4092 /* all args must be consumed */
4093 if (goi.argc != 0)
4095 return JIM_ERR;
4098 jim_wide b = 1; /* shut up gcc */
4099 if (strcasecmp(cmd_name, "mdw") == 0)
4100 b = 4;
4101 else if (strcasecmp(cmd_name, "mdh") == 0)
4102 b = 2;
4103 else if (strcasecmp(cmd_name, "mdb") == 0)
4104 b = 1;
4105 else {
4106 LOG_ERROR("command '%s' unknown: ", cmd_name);
4107 return JIM_ERR;
4110 /* convert count to "bytes" */
4111 c = c * b;
4113 struct target *target = Jim_CmdPrivData(goi.interp);
4114 uint8_t target_buf[32];
4115 jim_wide x, y, z;
4116 while (c > 0) {
4117 y = c;
4118 if (y > 16) {
4119 y = 16;
4121 e = fn(target, a, b, y / b, target_buf);
4122 if (e != ERROR_OK) {
4123 char tmp[10];
4124 snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4125 Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4126 return JIM_ERR;
4129 command_print(NULL, "0x%08x ", (int)(a));
4130 switch (b) {
4131 case 4:
4132 for (x = 0; x < 16 && x < y; x += 4)
4134 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4135 command_print(NULL, "%08x ", (int)(z));
4137 for (; (x < 16) ; x += 4) {
4138 command_print(NULL, " ");
4140 break;
4141 case 2:
4142 for (x = 0; x < 16 && x < y; x += 2)
4144 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4145 command_print(NULL, "%04x ", (int)(z));
4147 for (; (x < 16) ; x += 2) {
4148 command_print(NULL, " ");
4150 break;
4151 case 1:
4152 default:
4153 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4154 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4155 command_print(NULL, "%02x ", (int)(z));
4157 for (; (x < 16) ; x += 1) {
4158 command_print(NULL, " ");
4160 break;
4162 /* ascii-ify the bytes */
4163 for (x = 0 ; x < y ; x++) {
4164 if ((target_buf[x] >= 0x20) &&
4165 (target_buf[x] <= 0x7e)) {
4166 /* good */
4167 } else {
4168 /* smack it */
4169 target_buf[x] = '.';
4172 /* space pad */
4173 while (x < 16) {
4174 target_buf[x] = ' ';
4175 x++;
4177 /* terminate */
4178 target_buf[16] = 0;
4179 /* print - with a newline */
4180 command_print(NULL, "%s\n", target_buf);
4181 /* NEXT... */
4182 c -= 16;
4183 a += 16;
4185 return JIM_OK;
4188 static int jim_target_mem2array(Jim_Interp *interp,
4189 int argc, Jim_Obj *const *argv)
4191 struct target *target = Jim_CmdPrivData(interp);
4192 return target_mem2array(interp, target, argc - 1, argv + 1);
4195 static int jim_target_array2mem(Jim_Interp *interp,
4196 int argc, Jim_Obj *const *argv)
4198 struct target *target = Jim_CmdPrivData(interp);
4199 return target_array2mem(interp, target, argc - 1, argv + 1);
4202 static int jim_target_tap_disabled(Jim_Interp *interp)
4204 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4205 return JIM_ERR;
4208 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4210 if (argc != 1)
4212 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4213 return JIM_ERR;
4215 struct target *target = Jim_CmdPrivData(interp);
4216 if (!target->tap->enabled)
4217 return jim_target_tap_disabled(interp);
4219 int e = target->type->examine(target);
4220 if (e != ERROR_OK)
4222 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4223 Jim_SetResultFormatted(interp, "examine-fails: %#s", eObj);
4224 Jim_FreeNewObj(interp, eObj);
4225 return JIM_ERR;
4227 return JIM_OK;
4230 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4232 if (argc != 1)
4234 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4235 return JIM_ERR;
4237 struct target *target = Jim_CmdPrivData(interp);
4239 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4240 return JIM_ERR;
4242 return JIM_OK;
4245 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4247 if (argc != 1)
4249 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4250 return JIM_ERR;
4252 struct target *target = Jim_CmdPrivData(interp);
4253 if (!target->tap->enabled)
4254 return jim_target_tap_disabled(interp);
4256 int e;
4257 if (!(target_was_examined(target))) {
4258 e = ERROR_TARGET_NOT_EXAMINED;
4259 } else {
4260 e = target->type->poll(target);
4262 if (e != ERROR_OK)
4264 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4265 Jim_SetResultFormatted(interp, "poll-fails: %#s", eObj);
4266 Jim_FreeNewObj(interp, eObj);
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_SetResultFormatted(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_SetResultFormatted(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_Obj *eObj = Jim_NewIntObj(interp, e);
4372 Jim_SetResultFormatted(goi.interp,
4373 "target: %s wait %s fails (%#s) %s",
4374 target_name(target), n->name,
4375 eObj, target_strerror_safe(e));
4376 Jim_FreeNewObj(interp, eObj);
4377 return JIM_ERR;
4379 return JIM_OK;
4381 /* List for human, Events defined for this target.
4382 * scripts/programs should use 'name cget -event NAME'
4384 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4386 struct command_context *cmd_ctx = current_command_context(interp);
4387 assert (cmd_ctx != NULL);
4389 struct target *target = Jim_CmdPrivData(interp);
4390 struct target_event_action *teap = target->event_action;
4391 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4392 target->target_number,
4393 target_name(target));
4394 command_print(cmd_ctx, "%-25s | Body", "Event");
4395 command_print(cmd_ctx, "------------------------- | "
4396 "----------------------------------------");
4397 while (teap)
4399 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4400 command_print(cmd_ctx, "%-25s | %s",
4401 opt->name, Jim_GetString(teap->body, NULL));
4402 teap = teap->next;
4404 command_print(cmd_ctx, "***END***");
4405 return JIM_OK;
4407 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4409 if (argc != 1)
4411 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4412 return JIM_ERR;
4414 struct target *target = Jim_CmdPrivData(interp);
4415 Jim_SetResultString(interp, target_state_name(target), -1);
4416 return JIM_OK;
4418 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4420 Jim_GetOptInfo goi;
4421 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4422 if (goi.argc != 1)
4424 const char *cmd_name = Jim_GetString(argv[0], NULL);
4425 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4426 return JIM_ERR;
4428 Jim_Nvp *n;
4429 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4430 if (e != JIM_OK)
4432 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4433 return e;
4435 struct target *target = Jim_CmdPrivData(interp);
4436 target_handle_event(target, n->value);
4437 return JIM_OK;
4440 static const struct command_registration target_instance_command_handlers[] = {
4442 .name = "configure",
4443 .mode = COMMAND_CONFIG,
4444 .jim_handler = jim_target_configure,
4445 .help = "configure a new target for use",
4446 .usage = "[target_attribute ...]",
4449 .name = "cget",
4450 .mode = COMMAND_ANY,
4451 .jim_handler = jim_target_configure,
4452 .help = "returns the specified target attribute",
4453 .usage = "target_attribute",
4456 .name = "mww",
4457 .mode = COMMAND_EXEC,
4458 .jim_handler = jim_target_mw,
4459 .help = "Write 32-bit word(s) to target memory",
4460 .usage = "address data [count]",
4463 .name = "mwh",
4464 .mode = COMMAND_EXEC,
4465 .jim_handler = jim_target_mw,
4466 .help = "Write 16-bit half-word(s) to target memory",
4467 .usage = "address data [count]",
4470 .name = "mwb",
4471 .mode = COMMAND_EXEC,
4472 .jim_handler = jim_target_mw,
4473 .help = "Write byte(s) to target memory",
4474 .usage = "address data [count]",
4477 .name = "mdw",
4478 .mode = COMMAND_EXEC,
4479 .jim_handler = jim_target_md,
4480 .help = "Display target memory as 32-bit words",
4481 .usage = "address [count]",
4484 .name = "mdh",
4485 .mode = COMMAND_EXEC,
4486 .jim_handler = jim_target_md,
4487 .help = "Display target memory as 16-bit half-words",
4488 .usage = "address [count]",
4491 .name = "mdb",
4492 .mode = COMMAND_EXEC,
4493 .jim_handler = jim_target_md,
4494 .help = "Display target memory as 8-bit bytes",
4495 .usage = "address [count]",
4498 .name = "array2mem",
4499 .mode = COMMAND_EXEC,
4500 .jim_handler = jim_target_array2mem,
4501 .help = "Writes Tcl array of 8/16/32 bit numbers "
4502 "to target memory",
4503 .usage = "arrayname bitwidth address count",
4506 .name = "mem2array",
4507 .mode = COMMAND_EXEC,
4508 .jim_handler = jim_target_mem2array,
4509 .help = "Loads Tcl array of 8/16/32 bit numbers "
4510 "from target memory",
4511 .usage = "arrayname bitwidth address count",
4514 .name = "eventlist",
4515 .mode = COMMAND_EXEC,
4516 .jim_handler = jim_target_event_list,
4517 .help = "displays a table of events defined for this target",
4520 .name = "curstate",
4521 .mode = COMMAND_EXEC,
4522 .jim_handler = jim_target_current_state,
4523 .help = "displays the current state of this target",
4526 .name = "arp_examine",
4527 .mode = COMMAND_EXEC,
4528 .jim_handler = jim_target_examine,
4529 .help = "used internally for reset processing",
4532 .name = "arp_halt_gdb",
4533 .mode = COMMAND_EXEC,
4534 .jim_handler = jim_target_halt_gdb,
4535 .help = "used internally for reset processing to halt GDB",
4538 .name = "arp_poll",
4539 .mode = COMMAND_EXEC,
4540 .jim_handler = jim_target_poll,
4541 .help = "used internally for reset processing",
4544 .name = "arp_reset",
4545 .mode = COMMAND_EXEC,
4546 .jim_handler = jim_target_reset,
4547 .help = "used internally for reset processing",
4550 .name = "arp_halt",
4551 .mode = COMMAND_EXEC,
4552 .jim_handler = jim_target_halt,
4553 .help = "used internally for reset processing",
4556 .name = "arp_waitstate",
4557 .mode = COMMAND_EXEC,
4558 .jim_handler = jim_target_wait_state,
4559 .help = "used internally for reset processing",
4562 .name = "invoke-event",
4563 .mode = COMMAND_EXEC,
4564 .jim_handler = jim_target_invoke_event,
4565 .help = "invoke handler for specified event",
4566 .usage = "event_name",
4568 COMMAND_REGISTRATION_DONE
4571 static int target_create(Jim_GetOptInfo *goi)
4573 Jim_Obj *new_cmd;
4574 Jim_Cmd *cmd;
4575 const char *cp;
4576 char *cp2;
4577 int e;
4578 int x;
4579 struct target *target;
4580 struct command_context *cmd_ctx;
4582 cmd_ctx = current_command_context(goi->interp);
4583 assert (cmd_ctx != NULL);
4585 if (goi->argc < 3) {
4586 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4587 return JIM_ERR;
4590 /* COMMAND */
4591 Jim_GetOpt_Obj(goi, &new_cmd);
4592 /* does this command exist? */
4593 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4594 if (cmd) {
4595 cp = Jim_GetString(new_cmd, NULL);
4596 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4597 return JIM_ERR;
4600 /* TYPE */
4601 e = Jim_GetOpt_String(goi, &cp2, NULL);
4602 cp = cp2;
4603 /* now does target type exist */
4604 for (x = 0 ; target_types[x] ; x++) {
4605 if (0 == strcmp(cp, target_types[x]->name)) {
4606 /* found */
4607 break;
4610 if (target_types[x] == NULL) {
4611 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4612 for (x = 0 ; target_types[x] ; x++) {
4613 if (target_types[x + 1]) {
4614 Jim_AppendStrings(goi->interp,
4615 Jim_GetResult(goi->interp),
4616 target_types[x]->name,
4617 ", ", NULL);
4618 } else {
4619 Jim_AppendStrings(goi->interp,
4620 Jim_GetResult(goi->interp),
4621 " or ",
4622 target_types[x]->name,NULL);
4625 return JIM_ERR;
4628 /* Create it */
4629 target = calloc(1,sizeof(struct target));
4630 /* set target number */
4631 target->target_number = new_target_number();
4633 /* allocate memory for each unique target type */
4634 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4636 memcpy(target->type, target_types[x], sizeof(struct target_type));
4638 /* will be set by "-endian" */
4639 target->endianness = TARGET_ENDIAN_UNKNOWN;
4641 target->working_area = 0x0;
4642 target->working_area_size = 0x0;
4643 target->working_areas = NULL;
4644 target->backup_working_area = 0;
4646 target->state = TARGET_UNKNOWN;
4647 target->debug_reason = DBG_REASON_UNDEFINED;
4648 target->reg_cache = NULL;
4649 target->breakpoints = NULL;
4650 target->watchpoints = NULL;
4651 target->next = NULL;
4652 target->arch_info = NULL;
4654 target->display = 1;
4656 target->halt_issued = false;
4658 /* initialize trace information */
4659 target->trace_info = malloc(sizeof(struct trace));
4660 target->trace_info->num_trace_points = 0;
4661 target->trace_info->trace_points_size = 0;
4662 target->trace_info->trace_points = NULL;
4663 target->trace_info->trace_history_size = 0;
4664 target->trace_info->trace_history = NULL;
4665 target->trace_info->trace_history_pos = 0;
4666 target->trace_info->trace_history_overflowed = 0;
4668 target->dbgmsg = NULL;
4669 target->dbg_msg_enabled = 0;
4671 target->endianness = TARGET_ENDIAN_UNKNOWN;
4673 /* Do the rest as "configure" options */
4674 goi->isconfigure = 1;
4675 e = target_configure(goi, target);
4677 if (target->tap == NULL)
4679 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4680 e = JIM_ERR;
4683 if (e != JIM_OK) {
4684 free(target->type);
4685 free(target);
4686 return e;
4689 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4690 /* default endian to little if not specified */
4691 target->endianness = TARGET_LITTLE_ENDIAN;
4694 /* incase variant is not set */
4695 if (!target->variant)
4696 target->variant = strdup("");
4698 cp = Jim_GetString(new_cmd, NULL);
4699 target->cmd_name = strdup(cp);
4701 /* create the target specific commands */
4702 if (target->type->commands) {
4703 e = register_commands(cmd_ctx, NULL, target->type->commands);
4704 if (ERROR_OK != e)
4705 LOG_ERROR("unable to register '%s' commands", cp);
4707 if (target->type->target_create) {
4708 (*(target->type->target_create))(target, goi->interp);
4711 /* append to end of list */
4713 struct target **tpp;
4714 tpp = &(all_targets);
4715 while (*tpp) {
4716 tpp = &((*tpp)->next);
4718 *tpp = target;
4721 /* now - create the new target name command */
4722 const const struct command_registration target_subcommands[] = {
4724 .chain = target_instance_command_handlers,
4727 .chain = target->type->commands,
4729 COMMAND_REGISTRATION_DONE
4731 const const struct command_registration target_commands[] = {
4733 .name = cp,
4734 .mode = COMMAND_ANY,
4735 .help = "target command group",
4736 .chain = target_subcommands,
4738 COMMAND_REGISTRATION_DONE
4740 e = register_commands(cmd_ctx, NULL, target_commands);
4741 if (ERROR_OK != e)
4742 return JIM_ERR;
4744 struct command *c = command_find_in_context(cmd_ctx, cp);
4745 assert(c);
4746 command_set_handler_data(c, target);
4748 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4751 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4753 if (argc != 1)
4755 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4756 return JIM_ERR;
4758 struct command_context *cmd_ctx = current_command_context(interp);
4759 assert (cmd_ctx != NULL);
4761 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4762 return JIM_OK;
4765 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4767 if (argc != 1)
4769 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4770 return JIM_ERR;
4772 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4773 for (unsigned x = 0; NULL != target_types[x]; x++)
4775 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4776 Jim_NewStringObj(interp, target_types[x]->name, -1));
4778 return JIM_OK;
4781 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4783 if (argc != 1)
4785 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4786 return JIM_ERR;
4788 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4789 struct target *target = all_targets;
4790 while (target)
4792 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4793 Jim_NewStringObj(interp, target_name(target), -1));
4794 target = target->next;
4796 return JIM_OK;
4799 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4801 Jim_GetOptInfo goi;
4802 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4803 if (goi.argc < 3)
4805 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4806 "<name> <target_type> [<target_options> ...]");
4807 return JIM_ERR;
4809 return target_create(&goi);
4812 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4814 Jim_GetOptInfo goi;
4815 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4817 /* It's OK to remove this mechanism sometime after August 2010 or so */
4818 LOG_WARNING("don't use numbers as target identifiers; use names");
4819 if (goi.argc != 1)
4821 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
4822 return JIM_ERR;
4824 jim_wide w;
4825 int e = Jim_GetOpt_Wide(&goi, &w);
4826 if (e != JIM_OK)
4827 return JIM_ERR;
4829 struct target *target;
4830 for (target = all_targets; NULL != target; target = target->next)
4832 if (target->target_number != w)
4833 continue;
4835 Jim_SetResultString(goi.interp, target_name(target), -1);
4836 return JIM_OK;
4839 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
4840 Jim_SetResultFormatted(goi.interp,
4841 "Target: number %#s does not exist", wObj);
4842 Jim_FreeNewObj(interp, wObj);
4844 return JIM_ERR;
4847 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4849 if (argc != 1)
4851 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4852 return JIM_ERR;
4854 unsigned count = 0;
4855 struct target *target = all_targets;
4856 while (NULL != target)
4858 target = target->next;
4859 count++;
4861 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4862 return JIM_OK;
4865 static const struct command_registration target_subcommand_handlers[] = {
4867 .name = "init",
4868 .mode = COMMAND_CONFIG,
4869 .handler = handle_target_init_command,
4870 .help = "initialize targets",
4873 .name = "create",
4874 /* REVISIT this should be COMMAND_CONFIG ... */
4875 .mode = COMMAND_ANY,
4876 .jim_handler = jim_target_create,
4877 .usage = "name type '-chain-position' name [options ...]",
4878 .help = "Creates and selects a new target",
4881 .name = "current",
4882 .mode = COMMAND_ANY,
4883 .jim_handler = jim_target_current,
4884 .help = "Returns the currently selected target",
4887 .name = "types",
4888 .mode = COMMAND_ANY,
4889 .jim_handler = jim_target_types,
4890 .help = "Returns the available target types as "
4891 "a list of strings",
4894 .name = "names",
4895 .mode = COMMAND_ANY,
4896 .jim_handler = jim_target_names,
4897 .help = "Returns the names of all targets as a list of strings",
4900 .name = "number",
4901 .mode = COMMAND_ANY,
4902 .jim_handler = jim_target_number,
4903 .usage = "number",
4904 .help = "Returns the name of the numbered target "
4905 "(DEPRECATED)",
4908 .name = "count",
4909 .mode = COMMAND_ANY,
4910 .jim_handler = jim_target_count,
4911 .help = "Returns the number of targets as an integer "
4912 "(DEPRECATED)",
4914 COMMAND_REGISTRATION_DONE
4917 struct FastLoad
4919 uint32_t address;
4920 uint8_t *data;
4921 int length;
4925 static int fastload_num;
4926 static struct FastLoad *fastload;
4928 static void free_fastload(void)
4930 if (fastload != NULL)
4932 int i;
4933 for (i = 0; i < fastload_num; i++)
4935 if (fastload[i].data)
4936 free(fastload[i].data);
4938 free(fastload);
4939 fastload = NULL;
4946 COMMAND_HANDLER(handle_fast_load_image_command)
4948 uint8_t *buffer;
4949 size_t buf_cnt;
4950 uint32_t image_size;
4951 uint32_t min_address = 0;
4952 uint32_t max_address = 0xffffffff;
4953 int i;
4955 struct image image;
4957 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4958 &image, &min_address, &max_address);
4959 if (ERROR_OK != retval)
4960 return retval;
4962 struct duration bench;
4963 duration_start(&bench);
4965 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
4967 return ERROR_OK;
4970 image_size = 0x0;
4971 retval = ERROR_OK;
4972 fastload_num = image.num_sections;
4973 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4974 if (fastload == NULL)
4976 image_close(&image);
4977 return ERROR_FAIL;
4979 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4980 for (i = 0; i < image.num_sections; i++)
4982 buffer = malloc(image.sections[i].size);
4983 if (buffer == NULL)
4985 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
4986 (int)(image.sections[i].size));
4987 break;
4990 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4992 free(buffer);
4993 break;
4996 uint32_t offset = 0;
4997 uint32_t length = buf_cnt;
5000 /* DANGER!!! beware of unsigned comparision here!!! */
5002 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
5003 (image.sections[i].base_address < max_address))
5005 if (image.sections[i].base_address < min_address)
5007 /* clip addresses below */
5008 offset += min_address-image.sections[i].base_address;
5009 length -= offset;
5012 if (image.sections[i].base_address + buf_cnt > max_address)
5014 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5017 fastload[i].address = image.sections[i].base_address + offset;
5018 fastload[i].data = malloc(length);
5019 if (fastload[i].data == NULL)
5021 free(buffer);
5022 break;
5024 memcpy(fastload[i].data, buffer + offset, length);
5025 fastload[i].length = length;
5027 image_size += length;
5028 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5029 (unsigned int)length,
5030 ((unsigned int)(image.sections[i].base_address + offset)));
5033 free(buffer);
5036 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5038 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5039 "in %fs (%0.3f KiB/s)", image_size,
5040 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5042 command_print(CMD_CTX,
5043 "WARNING: image has not been loaded to target!"
5044 "You can issue a 'fast_load' to finish loading.");
5047 image_close(&image);
5049 if (retval != ERROR_OK)
5051 free_fastload();
5054 return retval;
5057 COMMAND_HANDLER(handle_fast_load_command)
5059 if (CMD_ARGC > 0)
5060 return ERROR_COMMAND_SYNTAX_ERROR;
5061 if (fastload == NULL)
5063 LOG_ERROR("No image in memory");
5064 return ERROR_FAIL;
5066 int i;
5067 int ms = timeval_ms();
5068 int size = 0;
5069 int retval = ERROR_OK;
5070 for (i = 0; i < fastload_num;i++)
5072 struct target *target = get_current_target(CMD_CTX);
5073 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5074 (unsigned int)(fastload[i].address),
5075 (unsigned int)(fastload[i].length));
5076 if (retval == ERROR_OK)
5078 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5080 size += fastload[i].length;
5082 int after = timeval_ms();
5083 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5084 return retval;
5087 static const struct command_registration target_command_handlers[] = {
5089 .name = "targets",
5090 .handler = handle_targets_command,
5091 .mode = COMMAND_ANY,
5092 .help = "change current default target (one parameter) "
5093 "or prints table of all targets (no parameters)",
5094 .usage = "[target]",
5097 .name = "target",
5098 .mode = COMMAND_CONFIG,
5099 .help = "configure target",
5101 .chain = target_subcommand_handlers,
5103 COMMAND_REGISTRATION_DONE
5106 int target_register_commands(struct command_context *cmd_ctx)
5108 return register_commands(cmd_ctx, NULL, target_command_handlers);
5111 static bool target_reset_nag = true;
5113 bool get_target_reset_nag(void)
5115 return target_reset_nag;
5118 COMMAND_HANDLER(handle_target_reset_nag)
5120 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5121 &target_reset_nag, "Nag after each reset about options to improve "
5122 "performance");
5125 static const struct command_registration target_exec_command_handlers[] = {
5127 .name = "fast_load_image",
5128 .handler = handle_fast_load_image_command,
5129 .mode = COMMAND_ANY,
5130 .help = "Load image into server memory for later use by "
5131 "fast_load; primarily for profiling",
5132 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5133 "[min_address [max_length]]",
5136 .name = "fast_load",
5137 .handler = handle_fast_load_command,
5138 .mode = COMMAND_EXEC,
5139 .help = "loads active fast load image to current target "
5140 "- mainly for profiling purposes",
5143 .name = "profile",
5144 .handler = handle_profile_command,
5145 .mode = COMMAND_EXEC,
5146 .help = "profiling samples the CPU PC",
5148 /** @todo don't register virt2phys() unless target supports it */
5150 .name = "virt2phys",
5151 .handler = handle_virt2phys_command,
5152 .mode = COMMAND_ANY,
5153 .help = "translate a virtual address into a physical address",
5154 .usage = "virtual_address",
5157 .name = "reg",
5158 .handler = handle_reg_command,
5159 .mode = COMMAND_EXEC,
5160 .help = "display or set a register; with no arguments, "
5161 "displays all registers and their values",
5162 .usage = "[(register_name|register_number) [value]]",
5165 .name = "poll",
5166 .handler = handle_poll_command,
5167 .mode = COMMAND_EXEC,
5168 .help = "poll target state; or reconfigure background polling",
5169 .usage = "['on'|'off']",
5172 .name = "wait_halt",
5173 .handler = handle_wait_halt_command,
5174 .mode = COMMAND_EXEC,
5175 .help = "wait up to the specified number of milliseconds "
5176 "(default 5) for a previously requested halt",
5177 .usage = "[milliseconds]",
5180 .name = "halt",
5181 .handler = handle_halt_command,
5182 .mode = COMMAND_EXEC,
5183 .help = "request target to halt, then wait up to the specified"
5184 "number of milliseconds (default 5) for it to complete",
5185 .usage = "[milliseconds]",
5188 .name = "resume",
5189 .handler = handle_resume_command,
5190 .mode = COMMAND_EXEC,
5191 .help = "resume target execution from current PC or address",
5192 .usage = "[address]",
5195 .name = "reset",
5196 .handler = handle_reset_command,
5197 .mode = COMMAND_EXEC,
5198 .usage = "[run|halt|init]",
5199 .help = "Reset all targets into the specified mode."
5200 "Default reset mode is run, if not given.",
5203 .name = "soft_reset_halt",
5204 .handler = handle_soft_reset_halt_command,
5205 .mode = COMMAND_EXEC,
5206 .help = "halt the target and do a soft reset",
5209 .name = "step",
5210 .handler = handle_step_command,
5211 .mode = COMMAND_EXEC,
5212 .help = "step one instruction from current PC or address",
5213 .usage = "[address]",
5216 .name = "mdw",
5217 .handler = handle_md_command,
5218 .mode = COMMAND_EXEC,
5219 .help = "display memory words",
5220 .usage = "['phys'] address [count]",
5223 .name = "mdh",
5224 .handler = handle_md_command,
5225 .mode = COMMAND_EXEC,
5226 .help = "display memory half-words",
5227 .usage = "['phys'] address [count]",
5230 .name = "mdb",
5231 .handler = handle_md_command,
5232 .mode = COMMAND_EXEC,
5233 .help = "display memory bytes",
5234 .usage = "['phys'] address [count]",
5237 .name = "mww",
5238 .handler = handle_mw_command,
5239 .mode = COMMAND_EXEC,
5240 .help = "write memory word",
5241 .usage = "['phys'] address value [count]",
5244 .name = "mwh",
5245 .handler = handle_mw_command,
5246 .mode = COMMAND_EXEC,
5247 .help = "write memory half-word",
5248 .usage = "['phys'] address value [count]",
5251 .name = "mwb",
5252 .handler = handle_mw_command,
5253 .mode = COMMAND_EXEC,
5254 .help = "write memory byte",
5255 .usage = "['phys'] address value [count]",
5258 .name = "bp",
5259 .handler = handle_bp_command,
5260 .mode = COMMAND_EXEC,
5261 .help = "list or set hardware or software breakpoint",
5262 .usage = "[address length ['hw']]",
5265 .name = "rbp",
5266 .handler = handle_rbp_command,
5267 .mode = COMMAND_EXEC,
5268 .help = "remove breakpoint",
5269 .usage = "address",
5272 .name = "wp",
5273 .handler = handle_wp_command,
5274 .mode = COMMAND_EXEC,
5275 .help = "list (no params) or create watchpoints",
5276 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5279 .name = "rwp",
5280 .handler = handle_rwp_command,
5281 .mode = COMMAND_EXEC,
5282 .help = "remove watchpoint",
5283 .usage = "address",
5286 .name = "load_image",
5287 .handler = handle_load_image_command,
5288 .mode = COMMAND_EXEC,
5289 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5290 "[min_address] [max_length]",
5293 .name = "dump_image",
5294 .handler = handle_dump_image_command,
5295 .mode = COMMAND_EXEC,
5296 .usage = "filename address size",
5299 .name = "verify_image",
5300 .handler = handle_verify_image_command,
5301 .mode = COMMAND_EXEC,
5302 .usage = "filename [offset [type]]",
5305 .name = "test_image",
5306 .handler = handle_test_image_command,
5307 .mode = COMMAND_EXEC,
5308 .usage = "filename [offset [type]]",
5311 .name = "mem2array",
5312 .mode = COMMAND_EXEC,
5313 .jim_handler = jim_mem2array,
5314 .help = "read 8/16/32 bit memory and return as a TCL array "
5315 "for script processing",
5316 .usage = "arrayname bitwidth address count",
5319 .name = "array2mem",
5320 .mode = COMMAND_EXEC,
5321 .jim_handler = jim_array2mem,
5322 .help = "convert a TCL array to memory locations "
5323 "and write the 8/16/32 bit values",
5324 .usage = "arrayname bitwidth address count",
5327 .name = "reset_nag",
5328 .handler = handle_target_reset_nag,
5329 .mode = COMMAND_ANY,
5330 .help = "Nag after each reset about options that could have been "
5331 "enabled to improve performance. ",
5332 .usage = "['enable'|'disable']",
5334 COMMAND_REGISTRATION_DONE
5336 static int target_register_user_commands(struct command_context *cmd_ctx)
5338 int retval = ERROR_OK;
5339 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5340 return retval;
5342 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5343 return retval;
5346 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);