Fix a bunch of typos.
[openocd/ellerodev.git] / src / target / target.c
blobbe42b338fba3136d2cf23579edd193d8ab96a107
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 arm946e_target;
62 extern struct target_type arm926ejs_target;
63 extern struct target_type fa526_target;
64 extern struct target_type feroceon_target;
65 extern struct target_type dragonite_target;
66 extern struct target_type xscale_target;
67 extern struct target_type cortexm3_target;
68 extern struct target_type cortexa8_target;
69 extern struct target_type cortexa9_target;
70 extern struct target_type arm11_target;
71 extern struct target_type mips_m4k_target;
72 extern struct target_type avr_target;
73 extern struct target_type dsp563xx_target;
74 extern struct target_type testee_target;
75 extern struct target_type avr32_ap7k_target;
77 static struct target_type *target_types[] =
79 &arm7tdmi_target,
80 &arm9tdmi_target,
81 &arm920t_target,
82 &arm720t_target,
83 &arm966e_target,
84 &arm946e_target,
85 &arm926ejs_target,
86 &fa526_target,
87 &feroceon_target,
88 &dragonite_target,
89 &xscale_target,
90 &cortexm3_target,
91 &cortexa8_target,
92 &cortexa9_target,
93 &arm11_target,
94 &mips_m4k_target,
95 &avr_target,
96 &dsp563xx_target,
97 &testee_target,
98 &avr32_ap7k_target,
99 NULL,
102 struct target *all_targets = NULL;
103 static struct target_event_callback *target_event_callbacks = NULL;
104 static struct target_timer_callback *target_timer_callbacks = NULL;
105 static const int polling_interval = 100;
107 static const Jim_Nvp nvp_assert[] = {
108 { .name = "assert", NVP_ASSERT },
109 { .name = "deassert", NVP_DEASSERT },
110 { .name = "T", NVP_ASSERT },
111 { .name = "F", NVP_DEASSERT },
112 { .name = "t", NVP_ASSERT },
113 { .name = "f", NVP_DEASSERT },
114 { .name = NULL, .value = -1 }
117 static const Jim_Nvp nvp_error_target[] = {
118 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
119 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
120 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
121 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
122 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
123 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
124 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
125 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
126 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
127 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
128 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
129 { .value = -1, .name = NULL }
132 static const char *target_strerror_safe(int err)
134 const Jim_Nvp *n;
136 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
137 if (n->name == NULL) {
138 return "unknown";
139 } else {
140 return n->name;
144 static const Jim_Nvp nvp_target_event[] = {
145 { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
146 { .value = TARGET_EVENT_OLD_pre_resume , .name = "old-pre_resume" },
148 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
149 { .value = TARGET_EVENT_HALTED, .name = "halted" },
150 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
151 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
152 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
154 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
155 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
157 /* historical name */
159 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
161 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
162 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
163 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
164 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
165 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
166 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
167 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
168 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
169 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
170 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
171 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
173 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
174 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
176 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
177 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
179 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
180 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
182 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
183 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
185 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
186 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
188 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
189 { .value = TARGET_EVENT_RESUMED , .name = "resume-ok" },
190 { .value = TARGET_EVENT_RESUME_END , .name = "resume-end" },
192 { .name = NULL, .value = -1 }
195 static const Jim_Nvp nvp_target_state[] = {
196 { .name = "unknown", .value = TARGET_UNKNOWN },
197 { .name = "running", .value = TARGET_RUNNING },
198 { .name = "halted", .value = TARGET_HALTED },
199 { .name = "reset", .value = TARGET_RESET },
200 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
201 { .name = NULL, .value = -1 },
204 static const Jim_Nvp nvp_target_debug_reason [] = {
205 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
206 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
207 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
208 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
209 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
210 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
211 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
212 { .name = NULL, .value = -1 },
215 static const Jim_Nvp nvp_target_endian[] = {
216 { .name = "big", .value = TARGET_BIG_ENDIAN },
217 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
218 { .name = "be", .value = TARGET_BIG_ENDIAN },
219 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
220 { .name = NULL, .value = -1 },
223 static const Jim_Nvp nvp_reset_modes[] = {
224 { .name = "unknown", .value = RESET_UNKNOWN },
225 { .name = "run" , .value = RESET_RUN },
226 { .name = "halt" , .value = RESET_HALT },
227 { .name = "init" , .value = RESET_INIT },
228 { .name = NULL , .value = -1 },
231 const char *debug_reason_name(struct target *t)
233 const char *cp;
235 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
236 t->debug_reason)->name;
237 if (!cp) {
238 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
239 cp = "(*BUG*unknown*BUG*)";
241 return cp;
244 const char *
245 target_state_name( struct target *t )
247 const char *cp;
248 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
249 if( !cp ){
250 LOG_ERROR("Invalid target state: %d", (int)(t->state));
251 cp = "(*BUG*unknown*BUG*)";
253 return cp;
256 /* determine the number of the new target */
257 static int new_target_number(void)
259 struct target *t;
260 int x;
262 /* number is 0 based */
263 x = -1;
264 t = all_targets;
265 while (t) {
266 if (x < t->target_number) {
267 x = t->target_number;
269 t = t->next;
271 return x + 1;
274 /* read a uint32_t from a buffer in target memory endianness */
275 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
277 if (target->endianness == TARGET_LITTLE_ENDIAN)
278 return le_to_h_u32(buffer);
279 else
280 return be_to_h_u32(buffer);
283 /* read a uint24_t from a buffer in target memory endianness */
284 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
286 if (target->endianness == TARGET_LITTLE_ENDIAN)
287 return le_to_h_u24(buffer);
288 else
289 return be_to_h_u24(buffer);
292 /* read a uint16_t from a buffer in target memory endianness */
293 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
295 if (target->endianness == TARGET_LITTLE_ENDIAN)
296 return le_to_h_u16(buffer);
297 else
298 return be_to_h_u16(buffer);
301 /* read a uint8_t from a buffer in target memory endianness */
302 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
304 return *buffer & 0x0ff;
307 /* write a uint32_t to a buffer in target memory endianness */
308 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
310 if (target->endianness == TARGET_LITTLE_ENDIAN)
311 h_u32_to_le(buffer, value);
312 else
313 h_u32_to_be(buffer, value);
316 /* write a uint24_t to a buffer in target memory endianness */
317 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
319 if (target->endianness == TARGET_LITTLE_ENDIAN)
320 h_u24_to_le(buffer, value);
321 else
322 h_u24_to_be(buffer, value);
325 /* write a uint16_t to a buffer in target memory endianness */
326 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
328 if (target->endianness == TARGET_LITTLE_ENDIAN)
329 h_u16_to_le(buffer, value);
330 else
331 h_u16_to_be(buffer, value);
334 /* write a uint8_t to a buffer in target memory endianness */
335 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
337 *buffer = value;
340 /* return a pointer to a configured target; id is name or number */
341 struct target *get_target(const char *id)
343 struct target *target;
345 /* try as tcltarget name */
346 for (target = all_targets; target; target = target->next) {
347 if (target->cmd_name == NULL)
348 continue;
349 if (strcmp(id, target->cmd_name) == 0)
350 return target;
353 /* It's OK to remove this fallback sometime after August 2010 or so */
355 /* no match, try as number */
356 unsigned num;
357 if (parse_uint(id, &num) != ERROR_OK)
358 return NULL;
360 for (target = all_targets; target; target = target->next) {
361 if (target->target_number == (int)num) {
362 LOG_WARNING("use '%s' as target identifier, not '%u'",
363 target->cmd_name, num);
364 return target;
368 return NULL;
371 /* returns a pointer to the n-th configured target */
372 static struct target *get_target_by_num(int num)
374 struct target *target = all_targets;
376 while (target) {
377 if (target->target_number == num) {
378 return target;
380 target = target->next;
383 return NULL;
386 struct target* get_current_target(struct command_context *cmd_ctx)
388 struct target *target = get_target_by_num(cmd_ctx->current_target);
390 if (target == NULL)
392 LOG_ERROR("BUG: current_target out of bounds");
393 exit(-1);
396 return target;
399 int target_poll(struct target *target)
401 int retval;
403 /* We can't poll until after examine */
404 if (!target_was_examined(target))
406 /* Fail silently lest we pollute the log */
407 return ERROR_FAIL;
410 retval = target->type->poll(target);
411 if (retval != ERROR_OK)
412 return retval;
414 if (target->halt_issued)
416 if (target->state == TARGET_HALTED)
418 target->halt_issued = false;
419 } else
421 long long t = timeval_ms() - target->halt_issued_time;
422 if (t>1000)
424 target->halt_issued = false;
425 LOG_INFO("Halt timed out, wake up GDB.");
426 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
431 return ERROR_OK;
434 int target_halt(struct target *target)
436 int retval;
437 /* We can't poll until after examine */
438 if (!target_was_examined(target))
440 LOG_ERROR("Target not examined yet");
441 return ERROR_FAIL;
444 retval = target->type->halt(target);
445 if (retval != ERROR_OK)
446 return retval;
448 target->halt_issued = true;
449 target->halt_issued_time = timeval_ms();
451 return ERROR_OK;
455 * Make the target (re)start executing using its saved execution
456 * context (possibly with some modifications).
458 * @param target Which target should start executing.
459 * @param current True to use the target's saved program counter instead
460 * of the address parameter
461 * @param address Optionally used as the program counter.
462 * @param handle_breakpoints True iff breakpoints at the resumption PC
463 * should be skipped. (For example, maybe execution was stopped by
464 * such a breakpoint, in which case it would be counterprodutive to
465 * let it re-trigger.
466 * @param debug_execution False if all working areas allocated by OpenOCD
467 * should be released and/or restored to their original contents.
468 * (This would for example be true to run some downloaded "helper"
469 * algorithm code, which resides in one such working buffer and uses
470 * another for data storage.)
472 * @todo Resolve the ambiguity about what the "debug_execution" flag
473 * signifies. For example, Target implementations don't agree on how
474 * it relates to invalidation of the register cache, or to whether
475 * breakpoints and watchpoints should be enabled. (It would seem wrong
476 * to enable breakpoints when running downloaded "helper" algorithms
477 * (debug_execution true), since the breakpoints would be set to match
478 * target firmware being debugged, not the helper algorithm.... and
479 * enabling them could cause such helpers to malfunction (for example,
480 * by overwriting data with a breakpoint instruction. On the other
481 * hand the infrastructure for running such helpers might use this
482 * procedure but rely on hardware breakpoint to detect termination.)
484 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
486 int retval;
488 /* We can't poll until after examine */
489 if (!target_was_examined(target))
491 LOG_ERROR("Target not examined yet");
492 return ERROR_FAIL;
495 /* note that resume *must* be asynchronous. The CPU can halt before
496 * we poll. The CPU can even halt at the current PC as a result of
497 * a software breakpoint being inserted by (a bug?) the application.
499 if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
500 return retval;
502 return retval;
505 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
507 char buf[100];
508 int retval;
509 Jim_Nvp *n;
510 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
511 if (n->name == NULL) {
512 LOG_ERROR("invalid reset mode");
513 return ERROR_FAIL;
516 /* disable polling during reset to make reset event scripts
517 * more predictable, i.e. dr/irscan & pathmove in events will
518 * not have JTAG operations injected into the middle of a sequence.
520 bool save_poll = jtag_poll_get_enabled();
522 jtag_poll_set_enabled(false);
524 sprintf(buf, "ocd_process_reset %s", n->name);
525 retval = Jim_Eval(cmd_ctx->interp, buf);
527 jtag_poll_set_enabled(save_poll);
529 if (retval != JIM_OK) {
530 Jim_MakeErrorMessage(cmd_ctx->interp);
531 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
532 return ERROR_FAIL;
535 /* We want any events to be processed before the prompt */
536 retval = target_call_timer_callbacks_now();
538 struct target *target;
539 for (target = all_targets; target; target = target->next) {
540 target->type->check_reset(target);
543 return retval;
546 static int identity_virt2phys(struct target *target,
547 uint32_t virtual, uint32_t *physical)
549 *physical = virtual;
550 return ERROR_OK;
553 static int no_mmu(struct target *target, int *enabled)
555 *enabled = 0;
556 return ERROR_OK;
559 static int default_examine(struct target *target)
561 target_set_examined(target);
562 return ERROR_OK;
565 /* no check by default */
566 static int default_check_reset(struct target *target)
568 return ERROR_OK;
571 int target_examine_one(struct target *target)
573 return target->type->examine(target);
576 static int jtag_enable_callback(enum jtag_event event, void *priv)
578 struct target *target = priv;
580 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
581 return ERROR_OK;
583 jtag_unregister_event_callback(jtag_enable_callback, target);
584 return target_examine_one(target);
588 /* Targets that correctly implement init + examine, i.e.
589 * no communication with target during init:
591 * XScale
593 int target_examine(void)
595 int retval = ERROR_OK;
596 struct target *target;
598 for (target = all_targets; target; target = target->next)
600 /* defer examination, but don't skip it */
601 if (!target->tap->enabled) {
602 jtag_register_event_callback(jtag_enable_callback,
603 target);
604 continue;
606 if ((retval = target_examine_one(target)) != ERROR_OK)
607 return retval;
609 return retval;
611 const char *target_type_name(struct target *target)
613 return target->type->name;
616 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
618 if (!target_was_examined(target))
620 LOG_ERROR("Target not examined yet");
621 return ERROR_FAIL;
623 return target->type->write_memory_imp(target, address, size, count, buffer);
626 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
628 if (!target_was_examined(target))
630 LOG_ERROR("Target not examined yet");
631 return ERROR_FAIL;
633 return target->type->read_memory_imp(target, address, size, count, buffer);
636 static int target_soft_reset_halt_imp(struct target *target)
638 if (!target_was_examined(target))
640 LOG_ERROR("Target not examined yet");
641 return ERROR_FAIL;
643 if (!target->type->soft_reset_halt_imp) {
644 LOG_ERROR("Target %s does not support soft_reset_halt",
645 target_name(target));
646 return ERROR_FAIL;
648 return target->type->soft_reset_halt_imp(target);
652 * Downloads a target-specific native code algorithm to the target,
653 * and executes it. * Note that some targets may need to set up, enable,
654 * and tear down a breakpoint (hard or * soft) to detect algorithm
655 * termination, while others may support lower overhead schemes where
656 * soft breakpoints embedded in the algorithm automatically terminate the
657 * algorithm.
659 * @param target used to run the algorithm
660 * @param arch_info target-specific description of the algorithm.
662 int target_run_algorithm(struct target *target,
663 int num_mem_params, struct mem_param *mem_params,
664 int num_reg_params, struct reg_param *reg_param,
665 uint32_t entry_point, uint32_t exit_point,
666 int timeout_ms, void *arch_info)
668 int retval = ERROR_FAIL;
670 if (!target_was_examined(target))
672 LOG_ERROR("Target not examined yet");
673 goto done;
675 if (!target->type->run_algorithm) {
676 LOG_ERROR("Target type '%s' does not support %s",
677 target_type_name(target), __func__);
678 goto done;
681 target->running_alg = true;
682 retval = target->type->run_algorithm(target,
683 num_mem_params, mem_params,
684 num_reg_params, reg_param,
685 entry_point, exit_point, timeout_ms, arch_info);
686 target->running_alg = false;
688 done:
689 return retval;
693 int target_read_memory(struct target *target,
694 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
696 return target->type->read_memory(target, address, size, count, buffer);
699 static int target_read_phys_memory(struct target *target,
700 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
702 return target->type->read_phys_memory(target, address, size, count, buffer);
705 int target_write_memory(struct target *target,
706 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
708 return target->type->write_memory(target, address, size, count, buffer);
711 static int target_write_phys_memory(struct target *target,
712 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
714 return target->type->write_phys_memory(target, address, size, count, buffer);
717 int target_bulk_write_memory(struct target *target,
718 uint32_t address, uint32_t count, uint8_t *buffer)
720 return target->type->bulk_write_memory(target, address, count, buffer);
723 int target_add_breakpoint(struct target *target,
724 struct breakpoint *breakpoint)
726 if (target->state != TARGET_HALTED) {
727 LOG_WARNING("target %s is not halted", target->cmd_name);
728 return ERROR_TARGET_NOT_HALTED;
730 return target->type->add_breakpoint(target, breakpoint);
732 int target_remove_breakpoint(struct target *target,
733 struct breakpoint *breakpoint)
735 return target->type->remove_breakpoint(target, breakpoint);
738 int target_add_watchpoint(struct target *target,
739 struct watchpoint *watchpoint)
741 if (target->state != TARGET_HALTED) {
742 LOG_WARNING("target %s is not halted", target->cmd_name);
743 return ERROR_TARGET_NOT_HALTED;
745 return target->type->add_watchpoint(target, watchpoint);
747 int target_remove_watchpoint(struct target *target,
748 struct watchpoint *watchpoint)
750 return target->type->remove_watchpoint(target, watchpoint);
753 int target_get_gdb_reg_list(struct target *target,
754 struct reg **reg_list[], int *reg_list_size)
756 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
758 int target_step(struct target *target,
759 int current, uint32_t address, int handle_breakpoints)
761 return target->type->step(target, current, address, handle_breakpoints);
766 * Reset the @c examined flag for the given target.
767 * Pure paranoia -- targets are zeroed on allocation.
769 static void target_reset_examined(struct target *target)
771 target->examined = false;
774 static int
775 err_read_phys_memory(struct target *target, uint32_t address,
776 uint32_t size, uint32_t count, uint8_t *buffer)
778 LOG_ERROR("Not implemented: %s", __func__);
779 return ERROR_FAIL;
782 static int
783 err_write_phys_memory(struct target *target, uint32_t address,
784 uint32_t size, uint32_t count, uint8_t *buffer)
786 LOG_ERROR("Not implemented: %s", __func__);
787 return ERROR_FAIL;
790 static int handle_target(void *priv);
792 static int target_init_one(struct command_context *cmd_ctx,
793 struct target *target)
795 target_reset_examined(target);
797 struct target_type *type = target->type;
798 if (type->examine == NULL)
799 type->examine = default_examine;
801 if (type->check_reset== NULL)
802 type->check_reset = default_check_reset;
804 int retval = type->init_target(cmd_ctx, target);
805 if (ERROR_OK != retval)
807 LOG_ERROR("target '%s' init failed", target_name(target));
808 return retval;
812 * @todo get rid of those *memory_imp() methods, now that all
813 * callers are using target_*_memory() accessors ... and make
814 * sure the "physical" paths handle the same issues.
816 /* a non-invasive way(in terms of patches) to add some code that
817 * runs before the type->write/read_memory implementation
819 type->write_memory_imp = target->type->write_memory;
820 type->write_memory = target_write_memory_imp;
822 type->read_memory_imp = target->type->read_memory;
823 type->read_memory = target_read_memory_imp;
825 type->soft_reset_halt_imp = target->type->soft_reset_halt;
826 type->soft_reset_halt = target_soft_reset_halt_imp;
828 /* Sanity-check MMU support ... stub in what we must, to help
829 * implement it in stages, but warn if we need to do so.
831 if (type->mmu)
833 if (type->write_phys_memory == NULL)
835 LOG_ERROR("type '%s' is missing write_phys_memory",
836 type->name);
837 type->write_phys_memory = err_write_phys_memory;
839 if (type->read_phys_memory == NULL)
841 LOG_ERROR("type '%s' is missing read_phys_memory",
842 type->name);
843 type->read_phys_memory = err_read_phys_memory;
845 if (type->virt2phys == NULL)
847 LOG_ERROR("type '%s' is missing virt2phys", type->name);
848 type->virt2phys = identity_virt2phys;
851 else
853 /* Make sure no-MMU targets all behave the same: make no
854 * distinction between physical and virtual addresses, and
855 * ensure that virt2phys() is always an identity mapping.
857 if (type->write_phys_memory || type->read_phys_memory
858 || type->virt2phys)
860 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
863 type->mmu = no_mmu;
864 type->write_phys_memory = type->write_memory;
865 type->read_phys_memory = type->read_memory;
866 type->virt2phys = identity_virt2phys;
868 return ERROR_OK;
871 static int target_init(struct command_context *cmd_ctx)
873 struct target *target;
874 int retval;
876 for (target = all_targets; target; target = target->next)
878 retval = target_init_one(cmd_ctx, target);
879 if (ERROR_OK != retval)
880 return retval;
883 if (!all_targets)
884 return ERROR_OK;
886 retval = target_register_user_commands(cmd_ctx);
887 if (ERROR_OK != retval)
888 return retval;
890 retval = target_register_timer_callback(&handle_target,
891 polling_interval, 1, cmd_ctx->interp);
892 if (ERROR_OK != retval)
893 return retval;
895 return ERROR_OK;
898 COMMAND_HANDLER(handle_target_init_command)
900 if (CMD_ARGC != 0)
901 return ERROR_COMMAND_SYNTAX_ERROR;
903 static bool target_initialized = false;
904 if (target_initialized)
906 LOG_INFO("'target init' has already been called");
907 return ERROR_OK;
909 target_initialized = true;
911 LOG_DEBUG("Initializing targets...");
912 return target_init(CMD_CTX);
915 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
917 struct target_event_callback **callbacks_p = &target_event_callbacks;
919 if (callback == NULL)
921 return ERROR_INVALID_ARGUMENTS;
924 if (*callbacks_p)
926 while ((*callbacks_p)->next)
927 callbacks_p = &((*callbacks_p)->next);
928 callbacks_p = &((*callbacks_p)->next);
931 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
932 (*callbacks_p)->callback = callback;
933 (*callbacks_p)->priv = priv;
934 (*callbacks_p)->next = NULL;
936 return ERROR_OK;
939 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
941 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
942 struct timeval now;
944 if (callback == NULL)
946 return ERROR_INVALID_ARGUMENTS;
949 if (*callbacks_p)
951 while ((*callbacks_p)->next)
952 callbacks_p = &((*callbacks_p)->next);
953 callbacks_p = &((*callbacks_p)->next);
956 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
957 (*callbacks_p)->callback = callback;
958 (*callbacks_p)->periodic = periodic;
959 (*callbacks_p)->time_ms = time_ms;
961 gettimeofday(&now, NULL);
962 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
963 time_ms -= (time_ms % 1000);
964 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
965 if ((*callbacks_p)->when.tv_usec > 1000000)
967 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
968 (*callbacks_p)->when.tv_sec += 1;
971 (*callbacks_p)->priv = priv;
972 (*callbacks_p)->next = NULL;
974 return ERROR_OK;
977 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
979 struct target_event_callback **p = &target_event_callbacks;
980 struct target_event_callback *c = target_event_callbacks;
982 if (callback == NULL)
984 return ERROR_INVALID_ARGUMENTS;
987 while (c)
989 struct target_event_callback *next = c->next;
990 if ((c->callback == callback) && (c->priv == priv))
992 *p = next;
993 free(c);
994 return ERROR_OK;
996 else
997 p = &(c->next);
998 c = next;
1001 return ERROR_OK;
1004 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1006 struct target_timer_callback **p = &target_timer_callbacks;
1007 struct target_timer_callback *c = target_timer_callbacks;
1009 if (callback == NULL)
1011 return ERROR_INVALID_ARGUMENTS;
1014 while (c)
1016 struct target_timer_callback *next = c->next;
1017 if ((c->callback == callback) && (c->priv == priv))
1019 *p = next;
1020 free(c);
1021 return ERROR_OK;
1023 else
1024 p = &(c->next);
1025 c = next;
1028 return ERROR_OK;
1031 int target_call_event_callbacks(struct target *target, enum target_event event)
1033 struct target_event_callback *callback = target_event_callbacks;
1034 struct target_event_callback *next_callback;
1036 if (event == TARGET_EVENT_HALTED)
1038 /* execute early halted first */
1039 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1042 LOG_DEBUG("target event %i (%s)",
1043 event,
1044 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1046 target_handle_event(target, event);
1048 while (callback)
1050 next_callback = callback->next;
1051 callback->callback(target, event, callback->priv);
1052 callback = next_callback;
1055 return ERROR_OK;
1058 static int target_timer_callback_periodic_restart(
1059 struct target_timer_callback *cb, struct timeval *now)
1061 int time_ms = cb->time_ms;
1062 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1063 time_ms -= (time_ms % 1000);
1064 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1065 if (cb->when.tv_usec > 1000000)
1067 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1068 cb->when.tv_sec += 1;
1070 return ERROR_OK;
1073 static int target_call_timer_callback(struct target_timer_callback *cb,
1074 struct timeval *now)
1076 cb->callback(cb->priv);
1078 if (cb->periodic)
1079 return target_timer_callback_periodic_restart(cb, now);
1081 return target_unregister_timer_callback(cb->callback, cb->priv);
1084 static int target_call_timer_callbacks_check_time(int checktime)
1086 keep_alive();
1088 struct timeval now;
1089 gettimeofday(&now, NULL);
1091 struct target_timer_callback *callback = target_timer_callbacks;
1092 while (callback)
1094 // cleaning up may unregister and free this callback
1095 struct target_timer_callback *next_callback = callback->next;
1097 bool call_it = callback->callback &&
1098 ((!checktime && callback->periodic) ||
1099 now.tv_sec > callback->when.tv_sec ||
1100 (now.tv_sec == callback->when.tv_sec &&
1101 now.tv_usec >= callback->when.tv_usec));
1103 if (call_it)
1105 int retval = target_call_timer_callback(callback, &now);
1106 if (retval != ERROR_OK)
1107 return retval;
1110 callback = next_callback;
1113 return ERROR_OK;
1116 int target_call_timer_callbacks(void)
1118 return target_call_timer_callbacks_check_time(1);
1121 /* invoke periodic callbacks immediately */
1122 int target_call_timer_callbacks_now(void)
1124 return target_call_timer_callbacks_check_time(0);
1127 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1129 struct working_area *c = target->working_areas;
1130 struct working_area *new_wa = NULL;
1132 /* Reevaluate working area address based on MMU state*/
1133 if (target->working_areas == NULL)
1135 int retval;
1136 int enabled;
1138 retval = target->type->mmu(target, &enabled);
1139 if (retval != ERROR_OK)
1141 return retval;
1144 if (!enabled) {
1145 if (target->working_area_phys_spec) {
1146 LOG_DEBUG("MMU disabled, using physical "
1147 "address for working memory 0x%08x",
1148 (unsigned)target->working_area_phys);
1149 target->working_area = target->working_area_phys;
1150 } else {
1151 LOG_ERROR("No working memory available. "
1152 "Specify -work-area-phys to target.");
1153 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1155 } else {
1156 if (target->working_area_virt_spec) {
1157 LOG_DEBUG("MMU enabled, using virtual "
1158 "address for working memory 0x%08x",
1159 (unsigned)target->working_area_virt);
1160 target->working_area = target->working_area_virt;
1161 } else {
1162 LOG_ERROR("No working memory available. "
1163 "Specify -work-area-virt to target.");
1164 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1169 /* only allocate multiples of 4 byte */
1170 if (size % 4)
1172 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1173 size = (size + 3) & (~3);
1176 /* see if there's already a matching working area */
1177 while (c)
1179 if ((c->free) && (c->size == size))
1181 new_wa = c;
1182 break;
1184 c = c->next;
1187 /* if not, allocate a new one */
1188 if (!new_wa)
1190 struct working_area **p = &target->working_areas;
1191 uint32_t first_free = target->working_area;
1192 uint32_t free_size = target->working_area_size;
1194 c = target->working_areas;
1195 while (c)
1197 first_free += c->size;
1198 free_size -= c->size;
1199 p = &c->next;
1200 c = c->next;
1203 if (free_size < size)
1205 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1208 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1210 new_wa = malloc(sizeof(struct working_area));
1211 new_wa->next = NULL;
1212 new_wa->size = size;
1213 new_wa->address = first_free;
1215 if (target->backup_working_area)
1217 int retval;
1218 new_wa->backup = malloc(new_wa->size);
1219 if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1221 free(new_wa->backup);
1222 free(new_wa);
1223 return retval;
1226 else
1228 new_wa->backup = NULL;
1231 /* put new entry in list */
1232 *p = new_wa;
1235 /* mark as used, and return the new (reused) area */
1236 new_wa->free = false;
1237 *area = new_wa;
1239 /* user pointer */
1240 new_wa->user = area;
1242 return ERROR_OK;
1245 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1247 int retval;
1249 retval = target_alloc_working_area_try(target, size, area);
1250 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1252 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1254 return retval;
1258 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1260 if (area->free)
1261 return ERROR_OK;
1263 if (restore && target->backup_working_area)
1265 int retval;
1266 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1267 return retval;
1270 area->free = true;
1272 /* mark user pointer invalid */
1273 *area->user = NULL;
1274 area->user = NULL;
1276 return ERROR_OK;
1279 int target_free_working_area(struct target *target, struct working_area *area)
1281 return target_free_working_area_restore(target, area, 1);
1284 /* free resources and restore memory, if restoring memory fails,
1285 * free up resources anyway
1287 static void target_free_all_working_areas_restore(struct target *target, int restore)
1289 struct working_area *c = target->working_areas;
1291 while (c)
1293 struct working_area *next = c->next;
1294 target_free_working_area_restore(target, c, restore);
1296 if (c->backup)
1297 free(c->backup);
1299 free(c);
1301 c = next;
1304 target->working_areas = NULL;
1307 void target_free_all_working_areas(struct target *target)
1309 target_free_all_working_areas_restore(target, 1);
1312 int target_arch_state(struct target *target)
1314 int retval;
1315 if (target == NULL)
1317 LOG_USER("No target has been configured");
1318 return ERROR_OK;
1321 LOG_USER("target state: %s", target_state_name( target ));
1323 if (target->state != TARGET_HALTED)
1324 return ERROR_OK;
1326 retval = target->type->arch_state(target);
1327 return retval;
1330 /* Single aligned words are guaranteed to use 16 or 32 bit access
1331 * mode respectively, otherwise data is handled as quickly as
1332 * possible
1334 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1336 int retval;
1337 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1338 (int)size, (unsigned)address);
1340 if (!target_was_examined(target))
1342 LOG_ERROR("Target not examined yet");
1343 return ERROR_FAIL;
1346 if (size == 0) {
1347 return ERROR_OK;
1350 if ((address + size - 1) < address)
1352 /* GDB can request this when e.g. PC is 0xfffffffc*/
1353 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1354 (unsigned)address,
1355 (unsigned)size);
1356 return ERROR_FAIL;
1359 if (((address % 2) == 0) && (size == 2))
1361 return target_write_memory(target, address, 2, 1, buffer);
1364 /* handle unaligned head bytes */
1365 if (address % 4)
1367 uint32_t unaligned = 4 - (address % 4);
1369 if (unaligned > size)
1370 unaligned = size;
1372 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1373 return retval;
1375 buffer += unaligned;
1376 address += unaligned;
1377 size -= unaligned;
1380 /* handle aligned words */
1381 if (size >= 4)
1383 int aligned = size - (size % 4);
1385 /* use bulk writes above a certain limit. This may have to be changed */
1386 if (aligned > 128)
1388 if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1389 return retval;
1391 else
1393 if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1394 return retval;
1397 buffer += aligned;
1398 address += aligned;
1399 size -= aligned;
1402 /* handle tail writes of less than 4 bytes */
1403 if (size > 0)
1405 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1406 return retval;
1409 return ERROR_OK;
1412 /* Single aligned words are guaranteed to use 16 or 32 bit access
1413 * mode respectively, otherwise data is handled as quickly as
1414 * possible
1416 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1418 int retval;
1419 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1420 (int)size, (unsigned)address);
1422 if (!target_was_examined(target))
1424 LOG_ERROR("Target not examined yet");
1425 return ERROR_FAIL;
1428 if (size == 0) {
1429 return ERROR_OK;
1432 if ((address + size - 1) < address)
1434 /* GDB can request this when e.g. PC is 0xfffffffc*/
1435 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1436 address,
1437 size);
1438 return ERROR_FAIL;
1441 if (((address % 2) == 0) && (size == 2))
1443 return target_read_memory(target, address, 2, 1, buffer);
1446 /* handle unaligned head bytes */
1447 if (address % 4)
1449 uint32_t unaligned = 4 - (address % 4);
1451 if (unaligned > size)
1452 unaligned = size;
1454 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1455 return retval;
1457 buffer += unaligned;
1458 address += unaligned;
1459 size -= unaligned;
1462 /* handle aligned words */
1463 if (size >= 4)
1465 int aligned = size - (size % 4);
1467 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1468 return retval;
1470 buffer += aligned;
1471 address += aligned;
1472 size -= aligned;
1475 /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1476 if(size >=2)
1478 int aligned = size - (size%2);
1479 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1480 if (retval != ERROR_OK)
1481 return retval;
1483 buffer += aligned;
1484 address += aligned;
1485 size -= aligned;
1487 /* handle tail writes of less than 4 bytes */
1488 if (size > 0)
1490 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1491 return retval;
1494 return ERROR_OK;
1497 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1499 uint8_t *buffer;
1500 int retval;
1501 uint32_t i;
1502 uint32_t checksum = 0;
1503 if (!target_was_examined(target))
1505 LOG_ERROR("Target not examined yet");
1506 return ERROR_FAIL;
1509 if ((retval = target->type->checksum_memory(target, address,
1510 size, &checksum)) != ERROR_OK)
1512 buffer = malloc(size);
1513 if (buffer == NULL)
1515 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1516 return ERROR_INVALID_ARGUMENTS;
1518 retval = target_read_buffer(target, address, size, buffer);
1519 if (retval != ERROR_OK)
1521 free(buffer);
1522 return retval;
1525 /* convert to target endianness */
1526 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1528 uint32_t target_data;
1529 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1530 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1533 retval = image_calculate_checksum(buffer, size, &checksum);
1534 free(buffer);
1537 *crc = checksum;
1539 return retval;
1542 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1544 int retval;
1545 if (!target_was_examined(target))
1547 LOG_ERROR("Target not examined yet");
1548 return ERROR_FAIL;
1551 if (target->type->blank_check_memory == 0)
1552 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1554 retval = target->type->blank_check_memory(target, address, size, blank);
1556 return retval;
1559 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1561 uint8_t value_buf[4];
1562 if (!target_was_examined(target))
1564 LOG_ERROR("Target not examined yet");
1565 return ERROR_FAIL;
1568 int retval = target_read_memory(target, address, 4, 1, value_buf);
1570 if (retval == ERROR_OK)
1572 *value = target_buffer_get_u32(target, value_buf);
1573 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1574 address,
1575 *value);
1577 else
1579 *value = 0x0;
1580 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1581 address);
1584 return retval;
1587 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1589 uint8_t value_buf[2];
1590 if (!target_was_examined(target))
1592 LOG_ERROR("Target not examined yet");
1593 return ERROR_FAIL;
1596 int retval = target_read_memory(target, address, 2, 1, value_buf);
1598 if (retval == ERROR_OK)
1600 *value = target_buffer_get_u16(target, value_buf);
1601 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1602 address,
1603 *value);
1605 else
1607 *value = 0x0;
1608 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1609 address);
1612 return retval;
1615 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1617 int retval = target_read_memory(target, address, 1, 1, value);
1618 if (!target_was_examined(target))
1620 LOG_ERROR("Target not examined yet");
1621 return ERROR_FAIL;
1624 if (retval == ERROR_OK)
1626 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1627 address,
1628 *value);
1630 else
1632 *value = 0x0;
1633 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1634 address);
1637 return retval;
1640 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1642 int retval;
1643 uint8_t value_buf[4];
1644 if (!target_was_examined(target))
1646 LOG_ERROR("Target not examined yet");
1647 return ERROR_FAIL;
1650 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1651 address,
1652 value);
1654 target_buffer_set_u32(target, value_buf, value);
1655 if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1657 LOG_DEBUG("failed: %i", retval);
1660 return retval;
1663 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1665 int retval;
1666 uint8_t value_buf[2];
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%8.8x",
1674 address,
1675 value);
1677 target_buffer_set_u16(target, value_buf, value);
1678 if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1680 LOG_DEBUG("failed: %i", retval);
1683 return retval;
1686 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1688 int retval;
1689 if (!target_was_examined(target))
1691 LOG_ERROR("Target not examined yet");
1692 return ERROR_FAIL;
1695 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1696 address, value);
1698 if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1700 LOG_DEBUG("failed: %i", retval);
1703 return retval;
1706 COMMAND_HANDLER(handle_targets_command)
1708 struct target *target = all_targets;
1710 if (CMD_ARGC == 1)
1712 target = get_target(CMD_ARGV[0]);
1713 if (target == NULL) {
1714 command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1715 goto DumpTargets;
1717 if (!target->tap->enabled) {
1718 command_print(CMD_CTX,"Target: TAP %s is disabled, "
1719 "can't be the current target\n",
1720 target->tap->dotted_name);
1721 return ERROR_FAIL;
1724 CMD_CTX->current_target = target->target_number;
1725 return ERROR_OK;
1727 DumpTargets:
1729 target = all_targets;
1730 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
1731 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
1732 while (target)
1734 const char *state;
1735 char marker = ' ';
1737 if (target->tap->enabled)
1738 state = target_state_name( target );
1739 else
1740 state = "tap-disabled";
1742 if (CMD_CTX->current_target == target->target_number)
1743 marker = '*';
1745 /* keep columns lined up to match the headers above */
1746 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1747 target->target_number,
1748 marker,
1749 target_name(target),
1750 target_type_name(target),
1751 Jim_Nvp_value2name_simple(nvp_target_endian,
1752 target->endianness)->name,
1753 target->tap->dotted_name,
1754 state);
1755 target = target->next;
1758 return ERROR_OK;
1761 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1763 static int powerDropout;
1764 static int srstAsserted;
1766 static int runPowerRestore;
1767 static int runPowerDropout;
1768 static int runSrstAsserted;
1769 static int runSrstDeasserted;
1771 static int sense_handler(void)
1773 static int prevSrstAsserted = 0;
1774 static int prevPowerdropout = 0;
1776 int retval;
1777 if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1778 return retval;
1780 int powerRestored;
1781 powerRestored = prevPowerdropout && !powerDropout;
1782 if (powerRestored)
1784 runPowerRestore = 1;
1787 long long current = timeval_ms();
1788 static long long lastPower = 0;
1789 int waitMore = lastPower + 2000 > current;
1790 if (powerDropout && !waitMore)
1792 runPowerDropout = 1;
1793 lastPower = current;
1796 if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1797 return retval;
1799 int srstDeasserted;
1800 srstDeasserted = prevSrstAsserted && !srstAsserted;
1802 static long long lastSrst = 0;
1803 waitMore = lastSrst + 2000 > current;
1804 if (srstDeasserted && !waitMore)
1806 runSrstDeasserted = 1;
1807 lastSrst = current;
1810 if (!prevSrstAsserted && srstAsserted)
1812 runSrstAsserted = 1;
1815 prevSrstAsserted = srstAsserted;
1816 prevPowerdropout = powerDropout;
1818 if (srstDeasserted || powerRestored)
1820 /* Other than logging the event we can't do anything here.
1821 * Issuing a reset is a particularly bad idea as we might
1822 * be inside a reset already.
1826 return ERROR_OK;
1829 static int backoff_times = 0;
1830 static int backoff_count = 0;
1832 /* process target state changes */
1833 static int handle_target(void *priv)
1835 Jim_Interp *interp = (Jim_Interp *)priv;
1836 int retval = ERROR_OK;
1838 if (!is_jtag_poll_safe())
1840 /* polling is disabled currently */
1841 return ERROR_OK;
1844 /* we do not want to recurse here... */
1845 static int recursive = 0;
1846 if (! recursive)
1848 recursive = 1;
1849 sense_handler();
1850 /* danger! running these procedures can trigger srst assertions and power dropouts.
1851 * We need to avoid an infinite loop/recursion here and we do that by
1852 * clearing the flags after running these events.
1854 int did_something = 0;
1855 if (runSrstAsserted)
1857 LOG_INFO("srst asserted detected, running srst_asserted proc.");
1858 Jim_Eval(interp, "srst_asserted");
1859 did_something = 1;
1861 if (runSrstDeasserted)
1863 Jim_Eval(interp, "srst_deasserted");
1864 did_something = 1;
1866 if (runPowerDropout)
1868 LOG_INFO("Power dropout detected, running power_dropout proc.");
1869 Jim_Eval(interp, "power_dropout");
1870 did_something = 1;
1872 if (runPowerRestore)
1874 Jim_Eval(interp, "power_restore");
1875 did_something = 1;
1878 if (did_something)
1880 /* clear detect flags */
1881 sense_handler();
1884 /* clear action flags */
1886 runSrstAsserted = 0;
1887 runSrstDeasserted = 0;
1888 runPowerRestore = 0;
1889 runPowerDropout = 0;
1891 recursive = 0;
1894 if (backoff_times > backoff_count)
1896 /* do not poll this time as we failed previously */
1897 backoff_count++;
1898 return ERROR_OK;
1900 backoff_count = 0;
1902 /* Poll targets for state changes unless that's globally disabled.
1903 * Skip targets that are currently disabled.
1905 for (struct target *target = all_targets;
1906 is_jtag_poll_safe() && target;
1907 target = target->next)
1909 if (!target->tap->enabled)
1910 continue;
1912 /* only poll target if we've got power and srst isn't asserted */
1913 if (!powerDropout && !srstAsserted)
1915 /* polling may fail silently until the target has been examined */
1916 if ((retval = target_poll(target)) != ERROR_OK)
1918 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1919 if (backoff_times * polling_interval < 5000)
1921 backoff_times *= 2;
1922 backoff_times++;
1924 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1926 /* Tell GDB to halt the debugger. This allows the user to
1927 * run monitor commands to handle the situation.
1929 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1930 return retval;
1932 /* Since we succeeded, we reset backoff count */
1933 if (backoff_times > 0)
1935 LOG_USER("Polling succeeded again");
1937 backoff_times = 0;
1941 return retval;
1944 COMMAND_HANDLER(handle_reg_command)
1946 struct target *target;
1947 struct reg *reg = NULL;
1948 unsigned count = 0;
1949 char *value;
1951 LOG_DEBUG("-");
1953 target = get_current_target(CMD_CTX);
1955 /* list all available registers for the current target */
1956 if (CMD_ARGC == 0)
1958 struct reg_cache *cache = target->reg_cache;
1960 count = 0;
1961 while (cache)
1963 unsigned i;
1965 command_print(CMD_CTX, "===== %s", cache->name);
1967 for (i = 0, reg = cache->reg_list;
1968 i < cache->num_regs;
1969 i++, reg++, count++)
1971 /* only print cached values if they are valid */
1972 if (reg->valid) {
1973 value = buf_to_str(reg->value,
1974 reg->size, 16);
1975 command_print(CMD_CTX,
1976 "(%i) %s (/%" PRIu32 "): 0x%s%s",
1977 count, reg->name,
1978 reg->size, value,
1979 reg->dirty
1980 ? " (dirty)"
1981 : "");
1982 free(value);
1983 } else {
1984 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1985 count, reg->name,
1986 reg->size) ;
1989 cache = cache->next;
1992 return ERROR_OK;
1995 /* access a single register by its ordinal number */
1996 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1998 unsigned num;
1999 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2001 struct reg_cache *cache = target->reg_cache;
2002 count = 0;
2003 while (cache)
2005 unsigned i;
2006 for (i = 0; i < cache->num_regs; i++)
2008 if (count++ == num)
2010 reg = &cache->reg_list[i];
2011 break;
2014 if (reg)
2015 break;
2016 cache = cache->next;
2019 if (!reg)
2021 command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2022 return ERROR_OK;
2024 } else /* access a single register by its name */
2026 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2028 if (!reg)
2030 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2031 return ERROR_OK;
2035 /* display a register */
2036 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2038 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2039 reg->valid = 0;
2041 if (reg->valid == 0)
2043 reg->type->get(reg);
2045 value = buf_to_str(reg->value, reg->size, 16);
2046 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2047 free(value);
2048 return ERROR_OK;
2051 /* set register value */
2052 if (CMD_ARGC == 2)
2054 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2055 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2057 reg->type->set(reg, buf);
2059 value = buf_to_str(reg->value, reg->size, 16);
2060 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2061 free(value);
2063 free(buf);
2065 return ERROR_OK;
2068 command_print(CMD_CTX, "usage: reg <#|name> [value]");
2070 return ERROR_OK;
2073 COMMAND_HANDLER(handle_poll_command)
2075 int retval = ERROR_OK;
2076 struct target *target = get_current_target(CMD_CTX);
2078 if (CMD_ARGC == 0)
2080 command_print(CMD_CTX, "background polling: %s",
2081 jtag_poll_get_enabled() ? "on" : "off");
2082 command_print(CMD_CTX, "TAP: %s (%s)",
2083 target->tap->dotted_name,
2084 target->tap->enabled ? "enabled" : "disabled");
2085 if (!target->tap->enabled)
2086 return ERROR_OK;
2087 if ((retval = target_poll(target)) != ERROR_OK)
2088 return retval;
2089 if ((retval = target_arch_state(target)) != ERROR_OK)
2090 return retval;
2092 else if (CMD_ARGC == 1)
2094 bool enable;
2095 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2096 jtag_poll_set_enabled(enable);
2098 else
2100 return ERROR_COMMAND_SYNTAX_ERROR;
2103 return retval;
2106 COMMAND_HANDLER(handle_wait_halt_command)
2108 if (CMD_ARGC > 1)
2109 return ERROR_COMMAND_SYNTAX_ERROR;
2111 unsigned ms = 5000;
2112 if (1 == CMD_ARGC)
2114 int retval = parse_uint(CMD_ARGV[0], &ms);
2115 if (ERROR_OK != retval)
2117 command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2118 return ERROR_COMMAND_SYNTAX_ERROR;
2120 // convert seconds (given) to milliseconds (needed)
2121 ms *= 1000;
2124 struct target *target = get_current_target(CMD_CTX);
2125 return target_wait_state(target, TARGET_HALTED, ms);
2128 /* wait for target state to change. The trick here is to have a low
2129 * latency for short waits and not to suck up all the CPU time
2130 * on longer waits.
2132 * After 500ms, keep_alive() is invoked
2134 int target_wait_state(struct target *target, enum target_state state, int ms)
2136 int retval;
2137 long long then = 0, cur;
2138 int once = 1;
2140 for (;;)
2142 if ((retval = target_poll(target)) != ERROR_OK)
2143 return retval;
2144 if (target->state == state)
2146 break;
2148 cur = timeval_ms();
2149 if (once)
2151 once = 0;
2152 then = timeval_ms();
2153 LOG_DEBUG("waiting for target %s...",
2154 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2157 if (cur-then > 500)
2159 keep_alive();
2162 if ((cur-then) > ms)
2164 LOG_ERROR("timed out while waiting for target %s",
2165 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2166 return ERROR_FAIL;
2170 return ERROR_OK;
2173 COMMAND_HANDLER(handle_halt_command)
2175 LOG_DEBUG("-");
2177 struct target *target = get_current_target(CMD_CTX);
2178 int retval = target_halt(target);
2179 if (ERROR_OK != retval)
2180 return retval;
2182 if (CMD_ARGC == 1)
2184 unsigned wait_local;
2185 retval = parse_uint(CMD_ARGV[0], &wait_local);
2186 if (ERROR_OK != retval)
2187 return ERROR_COMMAND_SYNTAX_ERROR;
2188 if (!wait_local)
2189 return ERROR_OK;
2192 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2195 COMMAND_HANDLER(handle_soft_reset_halt_command)
2197 struct target *target = get_current_target(CMD_CTX);
2199 LOG_USER("requesting target halt and executing a soft reset");
2201 target->type->soft_reset_halt(target);
2203 return ERROR_OK;
2206 COMMAND_HANDLER(handle_reset_command)
2208 if (CMD_ARGC > 1)
2209 return ERROR_COMMAND_SYNTAX_ERROR;
2211 enum target_reset_mode reset_mode = RESET_RUN;
2212 if (CMD_ARGC == 1)
2214 const Jim_Nvp *n;
2215 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2216 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2217 return ERROR_COMMAND_SYNTAX_ERROR;
2219 reset_mode = n->value;
2222 /* reset *all* targets */
2223 return target_process_reset(CMD_CTX, reset_mode);
2227 COMMAND_HANDLER(handle_resume_command)
2229 int current = 1;
2230 if (CMD_ARGC > 1)
2231 return ERROR_COMMAND_SYNTAX_ERROR;
2233 struct target *target = get_current_target(CMD_CTX);
2234 target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2236 /* with no CMD_ARGV, resume from current pc, addr = 0,
2237 * with one arguments, addr = CMD_ARGV[0],
2238 * handle breakpoints, not debugging */
2239 uint32_t addr = 0;
2240 if (CMD_ARGC == 1)
2242 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2243 current = 0;
2246 return target_resume(target, current, addr, 1, 0);
2249 COMMAND_HANDLER(handle_step_command)
2251 if (CMD_ARGC > 1)
2252 return ERROR_COMMAND_SYNTAX_ERROR;
2254 LOG_DEBUG("-");
2256 /* with no CMD_ARGV, step from current pc, addr = 0,
2257 * with one argument addr = CMD_ARGV[0],
2258 * handle breakpoints, debugging */
2259 uint32_t addr = 0;
2260 int current_pc = 1;
2261 if (CMD_ARGC == 1)
2263 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2264 current_pc = 0;
2267 struct target *target = get_current_target(CMD_CTX);
2269 return target->type->step(target, current_pc, addr, 1);
2272 static void handle_md_output(struct command_context *cmd_ctx,
2273 struct target *target, uint32_t address, unsigned size,
2274 unsigned count, const uint8_t *buffer)
2276 const unsigned line_bytecnt = 32;
2277 unsigned line_modulo = line_bytecnt / size;
2279 char output[line_bytecnt * 4 + 1];
2280 unsigned output_len = 0;
2282 const char *value_fmt;
2283 switch (size) {
2284 case 4: value_fmt = "%8.8x "; break;
2285 case 2: value_fmt = "%4.4x "; break;
2286 case 1: value_fmt = "%2.2x "; break;
2287 default:
2288 /* "can't happen", caller checked */
2289 LOG_ERROR("invalid memory read size: %u", size);
2290 return;
2293 for (unsigned i = 0; i < count; i++)
2295 if (i % line_modulo == 0)
2297 output_len += snprintf(output + output_len,
2298 sizeof(output) - output_len,
2299 "0x%8.8x: ",
2300 (unsigned)(address + (i*size)));
2303 uint32_t value = 0;
2304 const uint8_t *value_ptr = buffer + i * size;
2305 switch (size) {
2306 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2307 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2308 case 1: value = *value_ptr;
2310 output_len += snprintf(output + output_len,
2311 sizeof(output) - output_len,
2312 value_fmt, value);
2314 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2316 command_print(cmd_ctx, "%s", output);
2317 output_len = 0;
2322 COMMAND_HANDLER(handle_md_command)
2324 if (CMD_ARGC < 1)
2325 return ERROR_COMMAND_SYNTAX_ERROR;
2327 unsigned size = 0;
2328 switch (CMD_NAME[2]) {
2329 case 'w': size = 4; break;
2330 case 'h': size = 2; break;
2331 case 'b': size = 1; break;
2332 default: return ERROR_COMMAND_SYNTAX_ERROR;
2335 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2336 int (*fn)(struct target *target,
2337 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2338 if (physical)
2340 CMD_ARGC--;
2341 CMD_ARGV++;
2342 fn=target_read_phys_memory;
2343 } else
2345 fn=target_read_memory;
2347 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2349 return ERROR_COMMAND_SYNTAX_ERROR;
2352 uint32_t address;
2353 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2355 unsigned count = 1;
2356 if (CMD_ARGC == 2)
2357 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2359 uint8_t *buffer = calloc(count, size);
2361 struct target *target = get_current_target(CMD_CTX);
2362 int retval = fn(target, address, size, count, buffer);
2363 if (ERROR_OK == retval)
2364 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2366 free(buffer);
2368 return retval;
2371 typedef int (*target_write_fn)(struct target *target,
2372 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2374 static int target_write_memory_fast(struct target *target,
2375 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2377 return target_write_buffer(target, address, size * count, buffer);
2380 static int target_fill_mem(struct target *target,
2381 uint32_t address,
2382 target_write_fn fn,
2383 unsigned data_size,
2384 /* value */
2385 uint32_t b,
2386 /* count */
2387 unsigned c)
2389 /* We have to write in reasonably large chunks to be able
2390 * to fill large memory areas with any sane speed */
2391 const unsigned chunk_size = 16384;
2392 uint8_t *target_buf = malloc(chunk_size * data_size);
2393 if (target_buf == NULL)
2395 LOG_ERROR("Out of memory");
2396 return ERROR_FAIL;
2399 for (unsigned i = 0; i < chunk_size; i ++)
2401 switch (data_size)
2403 case 4:
2404 target_buffer_set_u32(target, target_buf + i*data_size, b);
2405 break;
2406 case 2:
2407 target_buffer_set_u16(target, target_buf + i*data_size, b);
2408 break;
2409 case 1:
2410 target_buffer_set_u8(target, target_buf + i*data_size, b);
2411 break;
2412 default:
2413 exit(-1);
2417 int retval = ERROR_OK;
2419 for (unsigned x = 0; x < c; x += chunk_size)
2421 unsigned current;
2422 current = c - x;
2423 if (current > chunk_size)
2425 current = chunk_size;
2427 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2428 if (retval != ERROR_OK)
2430 break;
2432 /* avoid GDB timeouts */
2433 keep_alive();
2435 free(target_buf);
2437 return retval;
2441 COMMAND_HANDLER(handle_mw_command)
2443 if (CMD_ARGC < 2)
2445 return ERROR_COMMAND_SYNTAX_ERROR;
2447 bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2448 target_write_fn fn;
2449 if (physical)
2451 CMD_ARGC--;
2452 CMD_ARGV++;
2453 fn=target_write_phys_memory;
2454 } else
2456 fn = target_write_memory_fast;
2458 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2459 return ERROR_COMMAND_SYNTAX_ERROR;
2461 uint32_t address;
2462 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2464 uint32_t value;
2465 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2467 unsigned count = 1;
2468 if (CMD_ARGC == 3)
2469 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2471 struct target *target = get_current_target(CMD_CTX);
2472 unsigned wordsize;
2473 switch (CMD_NAME[2])
2475 case 'w':
2476 wordsize = 4;
2477 break;
2478 case 'h':
2479 wordsize = 2;
2480 break;
2481 case 'b':
2482 wordsize = 1;
2483 break;
2484 default:
2485 return ERROR_COMMAND_SYNTAX_ERROR;
2488 return target_fill_mem(target, address, fn, wordsize, value, count);
2491 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2492 uint32_t *min_address, uint32_t *max_address)
2494 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2495 return ERROR_COMMAND_SYNTAX_ERROR;
2497 /* a base address isn't always necessary,
2498 * default to 0x0 (i.e. don't relocate) */
2499 if (CMD_ARGC >= 2)
2501 uint32_t addr;
2502 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2503 image->base_address = addr;
2504 image->base_address_set = 1;
2506 else
2507 image->base_address_set = 0;
2509 image->start_address_set = 0;
2511 if (CMD_ARGC >= 4)
2513 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2515 if (CMD_ARGC == 5)
2517 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2518 // use size (given) to find max (required)
2519 *max_address += *min_address;
2522 if (*min_address > *max_address)
2523 return ERROR_COMMAND_SYNTAX_ERROR;
2525 return ERROR_OK;
2528 COMMAND_HANDLER(handle_load_image_command)
2530 uint8_t *buffer;
2531 size_t buf_cnt;
2532 uint32_t image_size;
2533 uint32_t min_address = 0;
2534 uint32_t max_address = 0xffffffff;
2535 int i;
2536 struct image image;
2538 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2539 &image, &min_address, &max_address);
2540 if (ERROR_OK != retval)
2541 return retval;
2543 struct target *target = get_current_target(CMD_CTX);
2545 struct duration bench;
2546 duration_start(&bench);
2548 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2550 return ERROR_OK;
2553 image_size = 0x0;
2554 retval = ERROR_OK;
2555 for (i = 0; i < image.num_sections; i++)
2557 buffer = malloc(image.sections[i].size);
2558 if (buffer == NULL)
2560 command_print(CMD_CTX,
2561 "error allocating buffer for section (%d bytes)",
2562 (int)(image.sections[i].size));
2563 break;
2566 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2568 free(buffer);
2569 break;
2572 uint32_t offset = 0;
2573 uint32_t length = buf_cnt;
2575 /* DANGER!!! beware of unsigned comparision here!!! */
2577 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2578 (image.sections[i].base_address < max_address))
2580 if (image.sections[i].base_address < min_address)
2582 /* clip addresses below */
2583 offset += min_address-image.sections[i].base_address;
2584 length -= offset;
2587 if (image.sections[i].base_address + buf_cnt > max_address)
2589 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2592 if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2594 free(buffer);
2595 break;
2597 image_size += length;
2598 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2599 (unsigned int)length,
2600 image.sections[i].base_address + offset);
2603 free(buffer);
2606 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2608 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2609 "in %fs (%0.3f KiB/s)", image_size,
2610 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2613 image_close(&image);
2615 return retval;
2619 COMMAND_HANDLER(handle_dump_image_command)
2621 struct fileio fileio;
2622 uint8_t buffer[560];
2623 int retval, retvaltemp;
2624 uint32_t address, size;
2625 struct duration bench;
2626 struct target *target = get_current_target(CMD_CTX);
2628 if (CMD_ARGC != 3)
2629 return ERROR_COMMAND_SYNTAX_ERROR;
2631 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2632 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2634 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2635 if (retval != ERROR_OK)
2636 return retval;
2638 duration_start(&bench);
2640 retval = ERROR_OK;
2641 while (size > 0)
2643 size_t size_written;
2644 uint32_t this_run_size = (size > 560) ? 560 : size;
2645 retval = target_read_buffer(target, address, this_run_size, buffer);
2646 if (retval != ERROR_OK)
2648 break;
2651 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2652 if (retval != ERROR_OK)
2654 break;
2657 size -= this_run_size;
2658 address += this_run_size;
2661 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2663 int filesize;
2664 retval = fileio_size(&fileio, &filesize);
2665 if (retval != ERROR_OK)
2666 return retval;
2667 command_print(CMD_CTX,
2668 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2669 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2672 if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2673 return retvaltemp;
2675 return retval;
2678 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2680 uint8_t *buffer;
2681 size_t buf_cnt;
2682 uint32_t image_size;
2683 int i;
2684 int retval;
2685 uint32_t checksum = 0;
2686 uint32_t mem_checksum = 0;
2688 struct image image;
2690 struct target *target = get_current_target(CMD_CTX);
2692 if (CMD_ARGC < 1)
2694 return ERROR_COMMAND_SYNTAX_ERROR;
2697 if (!target)
2699 LOG_ERROR("no target selected");
2700 return ERROR_FAIL;
2703 struct duration bench;
2704 duration_start(&bench);
2706 if (CMD_ARGC >= 2)
2708 uint32_t addr;
2709 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2710 image.base_address = addr;
2711 image.base_address_set = 1;
2713 else
2715 image.base_address_set = 0;
2716 image.base_address = 0x0;
2719 image.start_address_set = 0;
2721 if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2723 return retval;
2726 image_size = 0x0;
2727 int diffs = 0;
2728 retval = ERROR_OK;
2729 for (i = 0; i < image.num_sections; i++)
2731 buffer = malloc(image.sections[i].size);
2732 if (buffer == NULL)
2734 command_print(CMD_CTX,
2735 "error allocating buffer for section (%d bytes)",
2736 (int)(image.sections[i].size));
2737 break;
2739 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2741 free(buffer);
2742 break;
2745 if (verify)
2747 /* calculate checksum of image */
2748 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2749 if (retval != ERROR_OK)
2751 free(buffer);
2752 break;
2755 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2756 if (retval != ERROR_OK)
2758 free(buffer);
2759 break;
2762 if (checksum != mem_checksum)
2764 /* failed crc checksum, fall back to a binary compare */
2765 uint8_t *data;
2767 if (diffs == 0)
2769 LOG_ERROR("checksum mismatch - attempting binary compare");
2772 data = (uint8_t*)malloc(buf_cnt);
2774 /* Can we use 32bit word accesses? */
2775 int size = 1;
2776 int count = buf_cnt;
2777 if ((count % 4) == 0)
2779 size *= 4;
2780 count /= 4;
2782 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2783 if (retval == ERROR_OK)
2785 uint32_t t;
2786 for (t = 0; t < buf_cnt; t++)
2788 if (data[t] != buffer[t])
2790 command_print(CMD_CTX,
2791 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2792 diffs,
2793 (unsigned)(t + image.sections[i].base_address),
2794 data[t],
2795 buffer[t]);
2796 if (diffs++ >= 127)
2798 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2799 free(data);
2800 free(buffer);
2801 goto done;
2804 keep_alive();
2807 free(data);
2809 } else
2811 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2812 image.sections[i].base_address,
2813 buf_cnt);
2816 free(buffer);
2817 image_size += buf_cnt;
2819 if (diffs > 0)
2821 command_print(CMD_CTX, "No more differences found.");
2823 done:
2824 if (diffs > 0)
2826 retval = ERROR_FAIL;
2828 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2830 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2831 "in %fs (%0.3f KiB/s)", image_size,
2832 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2835 image_close(&image);
2837 return retval;
2840 COMMAND_HANDLER(handle_verify_image_command)
2842 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2845 COMMAND_HANDLER(handle_test_image_command)
2847 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2850 static int handle_bp_command_list(struct command_context *cmd_ctx)
2852 struct target *target = get_current_target(cmd_ctx);
2853 struct breakpoint *breakpoint = target->breakpoints;
2854 while (breakpoint)
2856 if (breakpoint->type == BKPT_SOFT)
2858 char* buf = buf_to_str(breakpoint->orig_instr,
2859 breakpoint->length, 16);
2860 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2861 breakpoint->address,
2862 breakpoint->length,
2863 breakpoint->set, buf);
2864 free(buf);
2866 else
2868 command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2869 breakpoint->address,
2870 breakpoint->length, breakpoint->set);
2873 breakpoint = breakpoint->next;
2875 return ERROR_OK;
2878 static int handle_bp_command_set(struct command_context *cmd_ctx,
2879 uint32_t addr, uint32_t length, int hw)
2881 struct target *target = get_current_target(cmd_ctx);
2882 int retval = breakpoint_add(target, addr, length, hw);
2883 if (ERROR_OK == retval)
2884 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2885 else
2886 LOG_ERROR("Failure setting breakpoint");
2887 return retval;
2890 COMMAND_HANDLER(handle_bp_command)
2892 if (CMD_ARGC == 0)
2893 return handle_bp_command_list(CMD_CTX);
2895 if (CMD_ARGC < 2 || CMD_ARGC > 3)
2897 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2898 return ERROR_COMMAND_SYNTAX_ERROR;
2901 uint32_t addr;
2902 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2903 uint32_t length;
2904 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2906 int hw = BKPT_SOFT;
2907 if (CMD_ARGC == 3)
2909 if (strcmp(CMD_ARGV[2], "hw") == 0)
2910 hw = BKPT_HARD;
2911 else
2912 return ERROR_COMMAND_SYNTAX_ERROR;
2915 return handle_bp_command_set(CMD_CTX, addr, length, hw);
2918 COMMAND_HANDLER(handle_rbp_command)
2920 if (CMD_ARGC != 1)
2921 return ERROR_COMMAND_SYNTAX_ERROR;
2923 uint32_t addr;
2924 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2926 struct target *target = get_current_target(CMD_CTX);
2927 breakpoint_remove(target, addr);
2929 return ERROR_OK;
2932 COMMAND_HANDLER(handle_wp_command)
2934 struct target *target = get_current_target(CMD_CTX);
2936 if (CMD_ARGC == 0)
2938 struct watchpoint *watchpoint = target->watchpoints;
2940 while (watchpoint)
2942 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2943 ", len: 0x%8.8" PRIx32
2944 ", r/w/a: %i, value: 0x%8.8" PRIx32
2945 ", mask: 0x%8.8" PRIx32,
2946 watchpoint->address,
2947 watchpoint->length,
2948 (int)watchpoint->rw,
2949 watchpoint->value,
2950 watchpoint->mask);
2951 watchpoint = watchpoint->next;
2953 return ERROR_OK;
2956 enum watchpoint_rw type = WPT_ACCESS;
2957 uint32_t addr = 0;
2958 uint32_t length = 0;
2959 uint32_t data_value = 0x0;
2960 uint32_t data_mask = 0xffffffff;
2962 switch (CMD_ARGC)
2964 case 5:
2965 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2966 // fall through
2967 case 4:
2968 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2969 // fall through
2970 case 3:
2971 switch (CMD_ARGV[2][0])
2973 case 'r':
2974 type = WPT_READ;
2975 break;
2976 case 'w':
2977 type = WPT_WRITE;
2978 break;
2979 case 'a':
2980 type = WPT_ACCESS;
2981 break;
2982 default:
2983 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2984 return ERROR_COMMAND_SYNTAX_ERROR;
2986 // fall through
2987 case 2:
2988 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2989 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2990 break;
2992 default:
2993 command_print(CMD_CTX, "usage: wp [address length "
2994 "[(r|w|a) [value [mask]]]]");
2995 return ERROR_COMMAND_SYNTAX_ERROR;
2998 int retval = watchpoint_add(target, addr, length, type,
2999 data_value, data_mask);
3000 if (ERROR_OK != retval)
3001 LOG_ERROR("Failure setting watchpoints");
3003 return retval;
3006 COMMAND_HANDLER(handle_rwp_command)
3008 if (CMD_ARGC != 1)
3009 return ERROR_COMMAND_SYNTAX_ERROR;
3011 uint32_t addr;
3012 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3014 struct target *target = get_current_target(CMD_CTX);
3015 watchpoint_remove(target, addr);
3017 return ERROR_OK;
3022 * Translate a virtual address to a physical address.
3024 * The low-level target implementation must have logged a detailed error
3025 * which is forwarded to telnet/GDB session.
3027 COMMAND_HANDLER(handle_virt2phys_command)
3029 if (CMD_ARGC != 1)
3030 return ERROR_COMMAND_SYNTAX_ERROR;
3032 uint32_t va;
3033 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3034 uint32_t pa;
3036 struct target *target = get_current_target(CMD_CTX);
3037 int retval = target->type->virt2phys(target, va, &pa);
3038 if (retval == ERROR_OK)
3039 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3041 return retval;
3044 static void writeData(FILE *f, const void *data, size_t len)
3046 size_t written = fwrite(data, 1, len, f);
3047 if (written != len)
3048 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3051 static void writeLong(FILE *f, int l)
3053 int i;
3054 for (i = 0; i < 4; i++)
3056 char c = (l >> (i*8))&0xff;
3057 writeData(f, &c, 1);
3062 static void writeString(FILE *f, char *s)
3064 writeData(f, s, strlen(s));
3067 /* Dump a gmon.out histogram file. */
3068 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3070 uint32_t i;
3071 FILE *f = fopen(filename, "w");
3072 if (f == NULL)
3073 return;
3074 writeString(f, "gmon");
3075 writeLong(f, 0x00000001); /* Version */
3076 writeLong(f, 0); /* padding */
3077 writeLong(f, 0); /* padding */
3078 writeLong(f, 0); /* padding */
3080 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3081 writeData(f, &zero, 1);
3083 /* figure out bucket size */
3084 uint32_t min = samples[0];
3085 uint32_t max = samples[0];
3086 for (i = 0; i < sampleNum; i++)
3088 if (min > samples[i])
3090 min = samples[i];
3092 if (max < samples[i])
3094 max = samples[i];
3098 int addressSpace = (max-min + 1);
3100 static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3101 uint32_t length = addressSpace;
3102 if (length > maxBuckets)
3104 length = maxBuckets;
3106 int *buckets = malloc(sizeof(int)*length);
3107 if (buckets == NULL)
3109 fclose(f);
3110 return;
3112 memset(buckets, 0, sizeof(int)*length);
3113 for (i = 0; i < sampleNum;i++)
3115 uint32_t address = samples[i];
3116 long long a = address-min;
3117 long long b = length-1;
3118 long long c = addressSpace-1;
3119 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3120 buckets[index_t]++;
3123 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3124 writeLong(f, min); /* low_pc */
3125 writeLong(f, max); /* high_pc */
3126 writeLong(f, length); /* # of samples */
3127 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3128 writeString(f, "seconds");
3129 for (i = 0; i < (15-strlen("seconds")); i++)
3130 writeData(f, &zero, 1);
3131 writeString(f, "s");
3133 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3135 char *data = malloc(2*length);
3136 if (data != NULL)
3138 for (i = 0; i < length;i++)
3140 int val;
3141 val = buckets[i];
3142 if (val > 65535)
3144 val = 65535;
3146 data[i*2]=val&0xff;
3147 data[i*2 + 1]=(val >> 8)&0xff;
3149 free(buckets);
3150 writeData(f, data, length * 2);
3151 free(data);
3152 } else
3154 free(buckets);
3157 fclose(f);
3160 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3161 * which will be used as a random sampling of PC */
3162 COMMAND_HANDLER(handle_profile_command)
3164 struct target *target = get_current_target(CMD_CTX);
3165 struct timeval timeout, now;
3167 gettimeofday(&timeout, NULL);
3168 if (CMD_ARGC != 2)
3170 return ERROR_COMMAND_SYNTAX_ERROR;
3172 unsigned offset;
3173 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3175 timeval_add_time(&timeout, offset, 0);
3178 * @todo: Some cores let us sample the PC without the
3179 * annoying halt/resume step; for example, ARMv7 PCSR.
3180 * Provide a way to use that more efficient mechanism.
3183 command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3185 static const int maxSample = 10000;
3186 uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3187 if (samples == NULL)
3188 return ERROR_OK;
3190 int numSamples = 0;
3191 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3192 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3194 for (;;)
3196 int retval;
3197 target_poll(target);
3198 if (target->state == TARGET_HALTED)
3200 uint32_t t=*((uint32_t *)reg->value);
3201 samples[numSamples++]=t;
3202 retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3203 target_poll(target);
3204 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3205 } else if (target->state == TARGET_RUNNING)
3207 /* We want to quickly sample the PC. */
3208 if ((retval = target_halt(target)) != ERROR_OK)
3210 free(samples);
3211 return retval;
3213 } else
3215 command_print(CMD_CTX, "Target not halted or running");
3216 retval = ERROR_OK;
3217 break;
3219 if (retval != ERROR_OK)
3221 break;
3224 gettimeofday(&now, NULL);
3225 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3227 command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3228 if ((retval = target_poll(target)) != ERROR_OK)
3230 free(samples);
3231 return retval;
3233 if (target->state == TARGET_HALTED)
3235 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3237 if ((retval = target_poll(target)) != ERROR_OK)
3239 free(samples);
3240 return retval;
3242 writeGmon(samples, numSamples, CMD_ARGV[1]);
3243 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3244 break;
3247 free(samples);
3249 return ERROR_OK;
3252 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3254 char *namebuf;
3255 Jim_Obj *nameObjPtr, *valObjPtr;
3256 int result;
3258 namebuf = alloc_printf("%s(%d)", varname, idx);
3259 if (!namebuf)
3260 return JIM_ERR;
3262 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3263 valObjPtr = Jim_NewIntObj(interp, val);
3264 if (!nameObjPtr || !valObjPtr)
3266 free(namebuf);
3267 return JIM_ERR;
3270 Jim_IncrRefCount(nameObjPtr);
3271 Jim_IncrRefCount(valObjPtr);
3272 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3273 Jim_DecrRefCount(interp, nameObjPtr);
3274 Jim_DecrRefCount(interp, valObjPtr);
3275 free(namebuf);
3276 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3277 return result;
3280 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3282 struct command_context *context;
3283 struct target *target;
3285 context = current_command_context(interp);
3286 assert (context != NULL);
3288 target = get_current_target(context);
3289 if (target == NULL)
3291 LOG_ERROR("mem2array: no current target");
3292 return JIM_ERR;
3295 return target_mem2array(interp, target, argc-1, argv + 1);
3298 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3300 long l;
3301 uint32_t width;
3302 int len;
3303 uint32_t addr;
3304 uint32_t count;
3305 uint32_t v;
3306 const char *varname;
3307 int n, e, retval;
3308 uint32_t i;
3310 /* argv[1] = name of array to receive the data
3311 * argv[2] = desired width
3312 * argv[3] = memory address
3313 * argv[4] = count of times to read
3315 if (argc != 4) {
3316 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3317 return JIM_ERR;
3319 varname = Jim_GetString(argv[0], &len);
3320 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3322 e = Jim_GetLong(interp, argv[1], &l);
3323 width = l;
3324 if (e != JIM_OK) {
3325 return e;
3328 e = Jim_GetLong(interp, argv[2], &l);
3329 addr = l;
3330 if (e != JIM_OK) {
3331 return e;
3333 e = Jim_GetLong(interp, argv[3], &l);
3334 len = l;
3335 if (e != JIM_OK) {
3336 return e;
3338 switch (width) {
3339 case 8:
3340 width = 1;
3341 break;
3342 case 16:
3343 width = 2;
3344 break;
3345 case 32:
3346 width = 4;
3347 break;
3348 default:
3349 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3350 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3351 return JIM_ERR;
3353 if (len == 0) {
3354 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3355 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3356 return JIM_ERR;
3358 if ((addr + (len * width)) < addr) {
3359 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3360 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3361 return JIM_ERR;
3363 /* absurd transfer size? */
3364 if (len > 65536) {
3365 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3366 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3367 return JIM_ERR;
3370 if ((width == 1) ||
3371 ((width == 2) && ((addr & 1) == 0)) ||
3372 ((width == 4) && ((addr & 3) == 0))) {
3373 /* all is well */
3374 } else {
3375 char buf[100];
3376 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3377 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3378 addr,
3379 width);
3380 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3381 return JIM_ERR;
3384 /* Transfer loop */
3386 /* index counter */
3387 n = 0;
3389 size_t buffersize = 4096;
3390 uint8_t *buffer = malloc(buffersize);
3391 if (buffer == NULL)
3392 return JIM_ERR;
3394 /* assume ok */
3395 e = JIM_OK;
3396 while (len) {
3397 /* Slurp... in buffer size chunks */
3399 count = len; /* in objects.. */
3400 if (count > (buffersize/width)) {
3401 count = (buffersize/width);
3404 retval = target_read_memory(target, addr, width, count, buffer);
3405 if (retval != ERROR_OK) {
3406 /* BOO !*/
3407 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3408 (unsigned int)addr,
3409 (int)width,
3410 (int)count);
3411 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3412 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3413 e = JIM_ERR;
3414 len = 0;
3415 } else {
3416 v = 0; /* shut up gcc */
3417 for (i = 0 ;i < count ;i++, n++) {
3418 switch (width) {
3419 case 4:
3420 v = target_buffer_get_u32(target, &buffer[i*width]);
3421 break;
3422 case 2:
3423 v = target_buffer_get_u16(target, &buffer[i*width]);
3424 break;
3425 case 1:
3426 v = buffer[i] & 0x0ff;
3427 break;
3429 new_int_array_element(interp, varname, n, v);
3431 len -= count;
3435 free(buffer);
3437 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3439 return JIM_OK;
3442 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3444 char *namebuf;
3445 Jim_Obj *nameObjPtr, *valObjPtr;
3446 int result;
3447 long l;
3449 namebuf = alloc_printf("%s(%d)", varname, idx);
3450 if (!namebuf)
3451 return JIM_ERR;
3453 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3454 if (!nameObjPtr)
3456 free(namebuf);
3457 return JIM_ERR;
3460 Jim_IncrRefCount(nameObjPtr);
3461 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3462 Jim_DecrRefCount(interp, nameObjPtr);
3463 free(namebuf);
3464 if (valObjPtr == NULL)
3465 return JIM_ERR;
3467 result = Jim_GetLong(interp, valObjPtr, &l);
3468 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3469 *val = l;
3470 return result;
3473 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3475 struct command_context *context;
3476 struct target *target;
3478 context = current_command_context(interp);
3479 assert (context != NULL);
3481 target = get_current_target(context);
3482 if (target == NULL) {
3483 LOG_ERROR("array2mem: no current target");
3484 return JIM_ERR;
3487 return target_array2mem(interp,target, argc-1, argv + 1);
3490 static int target_array2mem(Jim_Interp *interp, struct target *target,
3491 int argc, Jim_Obj *const *argv)
3493 long l;
3494 uint32_t width;
3495 int len;
3496 uint32_t addr;
3497 uint32_t count;
3498 uint32_t v;
3499 const char *varname;
3500 int n, e, retval;
3501 uint32_t i;
3503 /* argv[1] = name of array to get the data
3504 * argv[2] = desired width
3505 * argv[3] = memory address
3506 * argv[4] = count to write
3508 if (argc != 4) {
3509 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3510 return JIM_ERR;
3512 varname = Jim_GetString(argv[0], &len);
3513 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3515 e = Jim_GetLong(interp, argv[1], &l);
3516 width = l;
3517 if (e != JIM_OK) {
3518 return e;
3521 e = Jim_GetLong(interp, argv[2], &l);
3522 addr = l;
3523 if (e != JIM_OK) {
3524 return e;
3526 e = Jim_GetLong(interp, argv[3], &l);
3527 len = l;
3528 if (e != JIM_OK) {
3529 return e;
3531 switch (width) {
3532 case 8:
3533 width = 1;
3534 break;
3535 case 16:
3536 width = 2;
3537 break;
3538 case 32:
3539 width = 4;
3540 break;
3541 default:
3542 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3543 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3544 return JIM_ERR;
3546 if (len == 0) {
3547 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3548 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3549 return JIM_ERR;
3551 if ((addr + (len * width)) < addr) {
3552 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3553 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3554 return JIM_ERR;
3556 /* absurd transfer size? */
3557 if (len > 65536) {
3558 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3559 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3560 return JIM_ERR;
3563 if ((width == 1) ||
3564 ((width == 2) && ((addr & 1) == 0)) ||
3565 ((width == 4) && ((addr & 3) == 0))) {
3566 /* all is well */
3567 } else {
3568 char buf[100];
3569 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3570 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3571 (unsigned int)addr,
3572 (int)width);
3573 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3574 return JIM_ERR;
3577 /* Transfer loop */
3579 /* index counter */
3580 n = 0;
3581 /* assume ok */
3582 e = JIM_OK;
3584 size_t buffersize = 4096;
3585 uint8_t *buffer = malloc(buffersize);
3586 if (buffer == NULL)
3587 return JIM_ERR;
3589 while (len) {
3590 /* Slurp... in buffer size chunks */
3592 count = len; /* in objects.. */
3593 if (count > (buffersize/width)) {
3594 count = (buffersize/width);
3597 v = 0; /* shut up gcc */
3598 for (i = 0 ;i < count ;i++, n++) {
3599 get_int_array_element(interp, varname, n, &v);
3600 switch (width) {
3601 case 4:
3602 target_buffer_set_u32(target, &buffer[i*width], v);
3603 break;
3604 case 2:
3605 target_buffer_set_u16(target, &buffer[i*width], v);
3606 break;
3607 case 1:
3608 buffer[i] = v & 0x0ff;
3609 break;
3612 len -= count;
3614 retval = target_write_memory(target, addr, width, count, buffer);
3615 if (retval != ERROR_OK) {
3616 /* BOO !*/
3617 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3618 (unsigned int)addr,
3619 (int)width,
3620 (int)count);
3621 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3622 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3623 e = JIM_ERR;
3624 len = 0;
3628 free(buffer);
3630 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3632 return JIM_OK;
3635 /* FIX? should we propagate errors here rather than printing them
3636 * and continuing?
3638 void target_handle_event(struct target *target, enum target_event e)
3640 struct target_event_action *teap;
3642 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3643 if (teap->event == e) {
3644 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3645 target->target_number,
3646 target_name(target),
3647 target_type_name(target),
3649 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3650 Jim_GetString(teap->body, NULL));
3651 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3653 Jim_MakeErrorMessage(teap->interp);
3654 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3661 * Returns true only if the target has a handler for the specified event.
3663 bool target_has_event_action(struct target *target, enum target_event event)
3665 struct target_event_action *teap;
3667 for (teap = target->event_action; teap != NULL; teap = teap->next) {
3668 if (teap->event == event)
3669 return true;
3671 return false;
3674 enum target_cfg_param {
3675 TCFG_TYPE,
3676 TCFG_EVENT,
3677 TCFG_WORK_AREA_VIRT,
3678 TCFG_WORK_AREA_PHYS,
3679 TCFG_WORK_AREA_SIZE,
3680 TCFG_WORK_AREA_BACKUP,
3681 TCFG_ENDIAN,
3682 TCFG_VARIANT,
3683 TCFG_COREID,
3684 TCFG_CHAIN_POSITION,
3687 static Jim_Nvp nvp_config_opts[] = {
3688 { .name = "-type", .value = TCFG_TYPE },
3689 { .name = "-event", .value = TCFG_EVENT },
3690 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
3691 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
3692 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
3693 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3694 { .name = "-endian" , .value = TCFG_ENDIAN },
3695 { .name = "-variant", .value = TCFG_VARIANT },
3696 { .name = "-coreid", .value = TCFG_COREID },
3697 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
3699 { .name = NULL, .value = -1 }
3702 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3704 Jim_Nvp *n;
3705 Jim_Obj *o;
3706 jim_wide w;
3707 char *cp;
3708 int e;
3710 /* parse config or cget options ... */
3711 while (goi->argc > 0) {
3712 Jim_SetEmptyResult(goi->interp);
3713 /* Jim_GetOpt_Debug(goi); */
3715 if (target->type->target_jim_configure) {
3716 /* target defines a configure function */
3717 /* target gets first dibs on parameters */
3718 e = (*(target->type->target_jim_configure))(target, goi);
3719 if (e == JIM_OK) {
3720 /* more? */
3721 continue;
3723 if (e == JIM_ERR) {
3724 /* An error */
3725 return e;
3727 /* otherwise we 'continue' below */
3729 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3730 if (e != JIM_OK) {
3731 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3732 return e;
3734 switch (n->value) {
3735 case TCFG_TYPE:
3736 /* not setable */
3737 if (goi->isconfigure) {
3738 Jim_SetResultFormatted(goi->interp,
3739 "not settable: %s", n->name);
3740 return JIM_ERR;
3741 } else {
3742 no_params:
3743 if (goi->argc != 0) {
3744 Jim_WrongNumArgs(goi->interp,
3745 goi->argc, goi->argv,
3746 "NO PARAMS");
3747 return JIM_ERR;
3750 Jim_SetResultString(goi->interp,
3751 target_type_name(target), -1);
3752 /* loop for more */
3753 break;
3754 case TCFG_EVENT:
3755 if (goi->argc == 0) {
3756 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3757 return JIM_ERR;
3760 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3761 if (e != JIM_OK) {
3762 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3763 return e;
3766 if (goi->isconfigure) {
3767 if (goi->argc != 1) {
3768 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3769 return JIM_ERR;
3771 } else {
3772 if (goi->argc != 0) {
3773 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3774 return JIM_ERR;
3779 struct target_event_action *teap;
3781 teap = target->event_action;
3782 /* replace existing? */
3783 while (teap) {
3784 if (teap->event == (enum target_event)n->value) {
3785 break;
3787 teap = teap->next;
3790 if (goi->isconfigure) {
3791 bool replace = true;
3792 if (teap == NULL) {
3793 /* create new */
3794 teap = calloc(1, sizeof(*teap));
3795 replace = false;
3797 teap->event = n->value;
3798 teap->interp = goi->interp;
3799 Jim_GetOpt_Obj(goi, &o);
3800 if (teap->body) {
3801 Jim_DecrRefCount(teap->interp, teap->body);
3803 teap->body = Jim_DuplicateObj(goi->interp, o);
3805 * FIXME:
3806 * Tcl/TK - "tk events" have a nice feature.
3807 * See the "BIND" command.
3808 * We should support that here.
3809 * You can specify %X and %Y in the event code.
3810 * The idea is: %T - target name.
3811 * The idea is: %N - target number
3812 * The idea is: %E - event name.
3814 Jim_IncrRefCount(teap->body);
3816 if (!replace)
3818 /* add to head of event list */
3819 teap->next = target->event_action;
3820 target->event_action = teap;
3822 Jim_SetEmptyResult(goi->interp);
3823 } else {
3824 /* get */
3825 if (teap == NULL) {
3826 Jim_SetEmptyResult(goi->interp);
3827 } else {
3828 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3832 /* loop for more */
3833 break;
3835 case TCFG_WORK_AREA_VIRT:
3836 if (goi->isconfigure) {
3837 target_free_all_working_areas(target);
3838 e = Jim_GetOpt_Wide(goi, &w);
3839 if (e != JIM_OK) {
3840 return e;
3842 target->working_area_virt = w;
3843 target->working_area_virt_spec = true;
3844 } else {
3845 if (goi->argc != 0) {
3846 goto no_params;
3849 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3850 /* loop for more */
3851 break;
3853 case TCFG_WORK_AREA_PHYS:
3854 if (goi->isconfigure) {
3855 target_free_all_working_areas(target);
3856 e = Jim_GetOpt_Wide(goi, &w);
3857 if (e != JIM_OK) {
3858 return e;
3860 target->working_area_phys = w;
3861 target->working_area_phys_spec = true;
3862 } else {
3863 if (goi->argc != 0) {
3864 goto no_params;
3867 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3868 /* loop for more */
3869 break;
3871 case TCFG_WORK_AREA_SIZE:
3872 if (goi->isconfigure) {
3873 target_free_all_working_areas(target);
3874 e = Jim_GetOpt_Wide(goi, &w);
3875 if (e != JIM_OK) {
3876 return e;
3878 target->working_area_size = w;
3879 } else {
3880 if (goi->argc != 0) {
3881 goto no_params;
3884 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3885 /* loop for more */
3886 break;
3888 case TCFG_WORK_AREA_BACKUP:
3889 if (goi->isconfigure) {
3890 target_free_all_working_areas(target);
3891 e = Jim_GetOpt_Wide(goi, &w);
3892 if (e != JIM_OK) {
3893 return e;
3895 /* make this exactly 1 or 0 */
3896 target->backup_working_area = (!!w);
3897 } else {
3898 if (goi->argc != 0) {
3899 goto no_params;
3902 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3903 /* loop for more e*/
3904 break;
3906 case TCFG_ENDIAN:
3907 if (goi->isconfigure) {
3908 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3909 if (e != JIM_OK) {
3910 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3911 return e;
3913 target->endianness = n->value;
3914 } else {
3915 if (goi->argc != 0) {
3916 goto no_params;
3919 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3920 if (n->name == NULL) {
3921 target->endianness = TARGET_LITTLE_ENDIAN;
3922 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3924 Jim_SetResultString(goi->interp, n->name, -1);
3925 /* loop for more */
3926 break;
3928 case TCFG_VARIANT:
3929 if (goi->isconfigure) {
3930 if (goi->argc < 1) {
3931 Jim_SetResultFormatted(goi->interp,
3932 "%s ?STRING?",
3933 n->name);
3934 return JIM_ERR;
3936 if (target->variant) {
3937 free((void *)(target->variant));
3939 e = Jim_GetOpt_String(goi, &cp, NULL);
3940 target->variant = strdup(cp);
3941 } else {
3942 if (goi->argc != 0) {
3943 goto no_params;
3946 Jim_SetResultString(goi->interp, target->variant,-1);
3947 /* loop for more */
3948 break;
3950 case TCFG_COREID:
3951 if (goi->isconfigure) {
3952 e = Jim_GetOpt_Wide(goi, &w);
3953 if (e != JIM_OK) {
3954 return e;
3956 target->coreid = (int)w;
3957 } else {
3958 if (goi->argc != 0) {
3959 goto no_params;
3962 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3963 /* loop for more */
3964 break;
3966 case TCFG_CHAIN_POSITION:
3967 if (goi->isconfigure) {
3968 Jim_Obj *o_t;
3969 struct jtag_tap *tap;
3970 target_free_all_working_areas(target);
3971 e = Jim_GetOpt_Obj(goi, &o_t);
3972 if (e != JIM_OK) {
3973 return e;
3975 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
3976 if (tap == NULL) {
3977 return JIM_ERR;
3979 /* make this exactly 1 or 0 */
3980 target->tap = tap;
3981 } else {
3982 if (goi->argc != 0) {
3983 goto no_params;
3986 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
3987 /* loop for more e*/
3988 break;
3990 } /* while (goi->argc) */
3993 /* done - we return */
3994 return JIM_OK;
3997 static int
3998 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4000 Jim_GetOptInfo goi;
4002 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4003 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4004 int need_args = 1 + goi.isconfigure;
4005 if (goi.argc < need_args)
4007 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4008 goi.isconfigure
4009 ? "missing: -option VALUE ..."
4010 : "missing: -option ...");
4011 return JIM_ERR;
4013 struct target *target = Jim_CmdPrivData(goi.interp);
4014 return target_configure(&goi, target);
4017 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4019 const char *cmd_name = Jim_GetString(argv[0], NULL);
4021 Jim_GetOptInfo goi;
4022 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4024 if (goi.argc < 2 || goi.argc > 4)
4026 Jim_SetResultFormatted(goi.interp,
4027 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4028 return JIM_ERR;
4031 target_write_fn fn;
4032 fn = target_write_memory_fast;
4034 int e;
4035 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4037 /* consume it */
4038 struct Jim_Obj *obj;
4039 e = Jim_GetOpt_Obj(&goi, &obj);
4040 if (e != JIM_OK)
4041 return e;
4043 fn = target_write_phys_memory;
4046 jim_wide a;
4047 e = Jim_GetOpt_Wide(&goi, &a);
4048 if (e != JIM_OK)
4049 return e;
4051 jim_wide b;
4052 e = Jim_GetOpt_Wide(&goi, &b);
4053 if (e != JIM_OK)
4054 return e;
4056 jim_wide c = 1;
4057 if (goi.argc == 1)
4059 e = Jim_GetOpt_Wide(&goi, &c);
4060 if (e != JIM_OK)
4061 return e;
4064 /* all args must be consumed */
4065 if (goi.argc != 0)
4067 return JIM_ERR;
4070 struct target *target = Jim_CmdPrivData(goi.interp);
4071 unsigned data_size;
4072 if (strcasecmp(cmd_name, "mww") == 0) {
4073 data_size = 4;
4075 else if (strcasecmp(cmd_name, "mwh") == 0) {
4076 data_size = 2;
4078 else if (strcasecmp(cmd_name, "mwb") == 0) {
4079 data_size = 1;
4080 } else {
4081 LOG_ERROR("command '%s' unknown: ", cmd_name);
4082 return JIM_ERR;
4085 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4088 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4090 const char *cmd_name = Jim_GetString(argv[0], NULL);
4092 Jim_GetOptInfo goi;
4093 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4095 if ((goi.argc < 1) || (goi.argc > 3))
4097 Jim_SetResultFormatted(goi.interp,
4098 "usage: %s [phys] <address> [<count>]", cmd_name);
4099 return JIM_ERR;
4102 int (*fn)(struct target *target,
4103 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4104 fn=target_read_memory;
4106 int e;
4107 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4109 /* consume it */
4110 struct Jim_Obj *obj;
4111 e = Jim_GetOpt_Obj(&goi, &obj);
4112 if (e != JIM_OK)
4113 return e;
4115 fn=target_read_phys_memory;
4118 jim_wide a;
4119 e = Jim_GetOpt_Wide(&goi, &a);
4120 if (e != JIM_OK) {
4121 return JIM_ERR;
4123 jim_wide c;
4124 if (goi.argc == 1) {
4125 e = Jim_GetOpt_Wide(&goi, &c);
4126 if (e != JIM_OK) {
4127 return JIM_ERR;
4129 } else {
4130 c = 1;
4133 /* all args must be consumed */
4134 if (goi.argc != 0)
4136 return JIM_ERR;
4139 jim_wide b = 1; /* shut up gcc */
4140 if (strcasecmp(cmd_name, "mdw") == 0)
4141 b = 4;
4142 else if (strcasecmp(cmd_name, "mdh") == 0)
4143 b = 2;
4144 else if (strcasecmp(cmd_name, "mdb") == 0)
4145 b = 1;
4146 else {
4147 LOG_ERROR("command '%s' unknown: ", cmd_name);
4148 return JIM_ERR;
4151 /* convert count to "bytes" */
4152 c = c * b;
4154 struct target *target = Jim_CmdPrivData(goi.interp);
4155 uint8_t target_buf[32];
4156 jim_wide x, y, z;
4157 while (c > 0) {
4158 y = c;
4159 if (y > 16) {
4160 y = 16;
4162 e = fn(target, a, b, y / b, target_buf);
4163 if (e != ERROR_OK) {
4164 char tmp[10];
4165 snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4166 Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4167 return JIM_ERR;
4170 command_print(NULL, "0x%08x ", (int)(a));
4171 switch (b) {
4172 case 4:
4173 for (x = 0; x < 16 && x < y; x += 4)
4175 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4176 command_print(NULL, "%08x ", (int)(z));
4178 for (; (x < 16) ; x += 4) {
4179 command_print(NULL, " ");
4181 break;
4182 case 2:
4183 for (x = 0; x < 16 && x < y; x += 2)
4185 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4186 command_print(NULL, "%04x ", (int)(z));
4188 for (; (x < 16) ; x += 2) {
4189 command_print(NULL, " ");
4191 break;
4192 case 1:
4193 default:
4194 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4195 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4196 command_print(NULL, "%02x ", (int)(z));
4198 for (; (x < 16) ; x += 1) {
4199 command_print(NULL, " ");
4201 break;
4203 /* ascii-ify the bytes */
4204 for (x = 0 ; x < y ; x++) {
4205 if ((target_buf[x] >= 0x20) &&
4206 (target_buf[x] <= 0x7e)) {
4207 /* good */
4208 } else {
4209 /* smack it */
4210 target_buf[x] = '.';
4213 /* space pad */
4214 while (x < 16) {
4215 target_buf[x] = ' ';
4216 x++;
4218 /* terminate */
4219 target_buf[16] = 0;
4220 /* print - with a newline */
4221 command_print(NULL, "%s\n", target_buf);
4222 /* NEXT... */
4223 c -= 16;
4224 a += 16;
4226 return JIM_OK;
4229 static int jim_target_mem2array(Jim_Interp *interp,
4230 int argc, Jim_Obj *const *argv)
4232 struct target *target = Jim_CmdPrivData(interp);
4233 return target_mem2array(interp, target, argc - 1, argv + 1);
4236 static int jim_target_array2mem(Jim_Interp *interp,
4237 int argc, Jim_Obj *const *argv)
4239 struct target *target = Jim_CmdPrivData(interp);
4240 return target_array2mem(interp, target, argc - 1, argv + 1);
4243 static int jim_target_tap_disabled(Jim_Interp *interp)
4245 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4246 return JIM_ERR;
4249 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4251 if (argc != 1)
4253 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4254 return JIM_ERR;
4256 struct target *target = Jim_CmdPrivData(interp);
4257 if (!target->tap->enabled)
4258 return jim_target_tap_disabled(interp);
4260 int e = target->type->examine(target);
4261 if (e != ERROR_OK)
4263 return JIM_ERR;
4265 return JIM_OK;
4268 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4270 if (argc != 1)
4272 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4273 return JIM_ERR;
4275 struct target *target = Jim_CmdPrivData(interp);
4277 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4278 return JIM_ERR;
4280 return JIM_OK;
4283 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4285 if (argc != 1)
4287 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4288 return JIM_ERR;
4290 struct target *target = Jim_CmdPrivData(interp);
4291 if (!target->tap->enabled)
4292 return jim_target_tap_disabled(interp);
4294 int e;
4295 if (!(target_was_examined(target))) {
4296 e = ERROR_TARGET_NOT_EXAMINED;
4297 } else {
4298 e = target->type->poll(target);
4300 if (e != ERROR_OK)
4302 return JIM_ERR;
4304 return JIM_OK;
4307 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4309 Jim_GetOptInfo goi;
4310 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4312 if (goi.argc != 2)
4314 Jim_WrongNumArgs(interp, 0, argv,
4315 "([tT]|[fF]|assert|deassert) BOOL");
4316 return JIM_ERR;
4319 Jim_Nvp *n;
4320 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4321 if (e != JIM_OK)
4323 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4324 return e;
4326 /* the halt or not param */
4327 jim_wide a;
4328 e = Jim_GetOpt_Wide(&goi, &a);
4329 if (e != JIM_OK)
4330 return e;
4332 struct target *target = Jim_CmdPrivData(goi.interp);
4333 if (!target->tap->enabled)
4334 return jim_target_tap_disabled(interp);
4335 if (!(target_was_examined(target)))
4337 LOG_ERROR("Target not examined yet");
4338 return ERROR_TARGET_NOT_EXAMINED;
4340 if (!target->type->assert_reset || !target->type->deassert_reset)
4342 Jim_SetResultFormatted(interp,
4343 "No target-specific reset for %s",
4344 target_name(target));
4345 return JIM_ERR;
4347 /* determine if we should halt or not. */
4348 target->reset_halt = !!a;
4349 /* When this happens - all workareas are invalid. */
4350 target_free_all_working_areas_restore(target, 0);
4352 /* do the assert */
4353 if (n->value == NVP_ASSERT) {
4354 e = target->type->assert_reset(target);
4355 } else {
4356 e = target->type->deassert_reset(target);
4358 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4361 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4363 if (argc != 1) {
4364 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4365 return JIM_ERR;
4367 struct target *target = Jim_CmdPrivData(interp);
4368 if (!target->tap->enabled)
4369 return jim_target_tap_disabled(interp);
4370 int e = target->type->halt(target);
4371 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4374 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4376 Jim_GetOptInfo goi;
4377 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4379 /* params: <name> statename timeoutmsecs */
4380 if (goi.argc != 2)
4382 const char *cmd_name = Jim_GetString(argv[0], NULL);
4383 Jim_SetResultFormatted(goi.interp,
4384 "%s <state_name> <timeout_in_msec>", cmd_name);
4385 return JIM_ERR;
4388 Jim_Nvp *n;
4389 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4390 if (e != JIM_OK) {
4391 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4392 return e;
4394 jim_wide a;
4395 e = Jim_GetOpt_Wide(&goi, &a);
4396 if (e != JIM_OK) {
4397 return e;
4399 struct target *target = Jim_CmdPrivData(interp);
4400 if (!target->tap->enabled)
4401 return jim_target_tap_disabled(interp);
4403 e = target_wait_state(target, n->value, a);
4404 if (e != ERROR_OK)
4406 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4407 Jim_SetResultFormatted(goi.interp,
4408 "target: %s wait %s fails (%#s) %s",
4409 target_name(target), n->name,
4410 eObj, target_strerror_safe(e));
4411 Jim_FreeNewObj(interp, eObj);
4412 return JIM_ERR;
4414 return JIM_OK;
4416 /* List for human, Events defined for this target.
4417 * scripts/programs should use 'name cget -event NAME'
4419 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4421 struct command_context *cmd_ctx = current_command_context(interp);
4422 assert (cmd_ctx != NULL);
4424 struct target *target = Jim_CmdPrivData(interp);
4425 struct target_event_action *teap = target->event_action;
4426 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4427 target->target_number,
4428 target_name(target));
4429 command_print(cmd_ctx, "%-25s | Body", "Event");
4430 command_print(cmd_ctx, "------------------------- | "
4431 "----------------------------------------");
4432 while (teap)
4434 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4435 command_print(cmd_ctx, "%-25s | %s",
4436 opt->name, Jim_GetString(teap->body, NULL));
4437 teap = teap->next;
4439 command_print(cmd_ctx, "***END***");
4440 return JIM_OK;
4442 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4444 if (argc != 1)
4446 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4447 return JIM_ERR;
4449 struct target *target = Jim_CmdPrivData(interp);
4450 Jim_SetResultString(interp, target_state_name(target), -1);
4451 return JIM_OK;
4453 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4455 Jim_GetOptInfo goi;
4456 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4457 if (goi.argc != 1)
4459 const char *cmd_name = Jim_GetString(argv[0], NULL);
4460 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4461 return JIM_ERR;
4463 Jim_Nvp *n;
4464 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4465 if (e != JIM_OK)
4467 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4468 return e;
4470 struct target *target = Jim_CmdPrivData(interp);
4471 target_handle_event(target, n->value);
4472 return JIM_OK;
4475 static const struct command_registration target_instance_command_handlers[] = {
4477 .name = "configure",
4478 .mode = COMMAND_CONFIG,
4479 .jim_handler = jim_target_configure,
4480 .help = "configure a new target for use",
4481 .usage = "[target_attribute ...]",
4484 .name = "cget",
4485 .mode = COMMAND_ANY,
4486 .jim_handler = jim_target_configure,
4487 .help = "returns the specified target attribute",
4488 .usage = "target_attribute",
4491 .name = "mww",
4492 .mode = COMMAND_EXEC,
4493 .jim_handler = jim_target_mw,
4494 .help = "Write 32-bit word(s) to target memory",
4495 .usage = "address data [count]",
4498 .name = "mwh",
4499 .mode = COMMAND_EXEC,
4500 .jim_handler = jim_target_mw,
4501 .help = "Write 16-bit half-word(s) to target memory",
4502 .usage = "address data [count]",
4505 .name = "mwb",
4506 .mode = COMMAND_EXEC,
4507 .jim_handler = jim_target_mw,
4508 .help = "Write byte(s) to target memory",
4509 .usage = "address data [count]",
4512 .name = "mdw",
4513 .mode = COMMAND_EXEC,
4514 .jim_handler = jim_target_md,
4515 .help = "Display target memory as 32-bit words",
4516 .usage = "address [count]",
4519 .name = "mdh",
4520 .mode = COMMAND_EXEC,
4521 .jim_handler = jim_target_md,
4522 .help = "Display target memory as 16-bit half-words",
4523 .usage = "address [count]",
4526 .name = "mdb",
4527 .mode = COMMAND_EXEC,
4528 .jim_handler = jim_target_md,
4529 .help = "Display target memory as 8-bit bytes",
4530 .usage = "address [count]",
4533 .name = "array2mem",
4534 .mode = COMMAND_EXEC,
4535 .jim_handler = jim_target_array2mem,
4536 .help = "Writes Tcl array of 8/16/32 bit numbers "
4537 "to target memory",
4538 .usage = "arrayname bitwidth address count",
4541 .name = "mem2array",
4542 .mode = COMMAND_EXEC,
4543 .jim_handler = jim_target_mem2array,
4544 .help = "Loads Tcl array of 8/16/32 bit numbers "
4545 "from target memory",
4546 .usage = "arrayname bitwidth address count",
4549 .name = "eventlist",
4550 .mode = COMMAND_EXEC,
4551 .jim_handler = jim_target_event_list,
4552 .help = "displays a table of events defined for this target",
4555 .name = "curstate",
4556 .mode = COMMAND_EXEC,
4557 .jim_handler = jim_target_current_state,
4558 .help = "displays the current state of this target",
4561 .name = "arp_examine",
4562 .mode = COMMAND_EXEC,
4563 .jim_handler = jim_target_examine,
4564 .help = "used internally for reset processing",
4567 .name = "arp_halt_gdb",
4568 .mode = COMMAND_EXEC,
4569 .jim_handler = jim_target_halt_gdb,
4570 .help = "used internally for reset processing to halt GDB",
4573 .name = "arp_poll",
4574 .mode = COMMAND_EXEC,
4575 .jim_handler = jim_target_poll,
4576 .help = "used internally for reset processing",
4579 .name = "arp_reset",
4580 .mode = COMMAND_EXEC,
4581 .jim_handler = jim_target_reset,
4582 .help = "used internally for reset processing",
4585 .name = "arp_halt",
4586 .mode = COMMAND_EXEC,
4587 .jim_handler = jim_target_halt,
4588 .help = "used internally for reset processing",
4591 .name = "arp_waitstate",
4592 .mode = COMMAND_EXEC,
4593 .jim_handler = jim_target_wait_state,
4594 .help = "used internally for reset processing",
4597 .name = "invoke-event",
4598 .mode = COMMAND_EXEC,
4599 .jim_handler = jim_target_invoke_event,
4600 .help = "invoke handler for specified event",
4601 .usage = "event_name",
4603 COMMAND_REGISTRATION_DONE
4606 static int target_create(Jim_GetOptInfo *goi)
4608 Jim_Obj *new_cmd;
4609 Jim_Cmd *cmd;
4610 const char *cp;
4611 char *cp2;
4612 int e;
4613 int x;
4614 struct target *target;
4615 struct command_context *cmd_ctx;
4617 cmd_ctx = current_command_context(goi->interp);
4618 assert (cmd_ctx != NULL);
4620 if (goi->argc < 3) {
4621 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4622 return JIM_ERR;
4625 /* COMMAND */
4626 Jim_GetOpt_Obj(goi, &new_cmd);
4627 /* does this command exist? */
4628 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4629 if (cmd) {
4630 cp = Jim_GetString(new_cmd, NULL);
4631 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4632 return JIM_ERR;
4635 /* TYPE */
4636 e = Jim_GetOpt_String(goi, &cp2, NULL);
4637 cp = cp2;
4638 /* now does target type exist */
4639 for (x = 0 ; target_types[x] ; x++) {
4640 if (0 == strcmp(cp, target_types[x]->name)) {
4641 /* found */
4642 break;
4645 if (target_types[x] == NULL) {
4646 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4647 for (x = 0 ; target_types[x] ; x++) {
4648 if (target_types[x + 1]) {
4649 Jim_AppendStrings(goi->interp,
4650 Jim_GetResult(goi->interp),
4651 target_types[x]->name,
4652 ", ", NULL);
4653 } else {
4654 Jim_AppendStrings(goi->interp,
4655 Jim_GetResult(goi->interp),
4656 " or ",
4657 target_types[x]->name,NULL);
4660 return JIM_ERR;
4663 /* Create it */
4664 target = calloc(1,sizeof(struct target));
4665 /* set target number */
4666 target->target_number = new_target_number();
4668 /* allocate memory for each unique target type */
4669 target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4671 memcpy(target->type, target_types[x], sizeof(struct target_type));
4673 /* will be set by "-endian" */
4674 target->endianness = TARGET_ENDIAN_UNKNOWN;
4676 /* default to first core, override with -coreid */
4677 target->coreid = 0;
4679 target->working_area = 0x0;
4680 target->working_area_size = 0x0;
4681 target->working_areas = NULL;
4682 target->backup_working_area = 0;
4684 target->state = TARGET_UNKNOWN;
4685 target->debug_reason = DBG_REASON_UNDEFINED;
4686 target->reg_cache = NULL;
4687 target->breakpoints = NULL;
4688 target->watchpoints = NULL;
4689 target->next = NULL;
4690 target->arch_info = NULL;
4692 target->display = 1;
4694 target->halt_issued = false;
4696 /* initialize trace information */
4697 target->trace_info = malloc(sizeof(struct trace));
4698 target->trace_info->num_trace_points = 0;
4699 target->trace_info->trace_points_size = 0;
4700 target->trace_info->trace_points = NULL;
4701 target->trace_info->trace_history_size = 0;
4702 target->trace_info->trace_history = NULL;
4703 target->trace_info->trace_history_pos = 0;
4704 target->trace_info->trace_history_overflowed = 0;
4706 target->dbgmsg = NULL;
4707 target->dbg_msg_enabled = 0;
4709 target->endianness = TARGET_ENDIAN_UNKNOWN;
4711 /* Do the rest as "configure" options */
4712 goi->isconfigure = 1;
4713 e = target_configure(goi, target);
4715 if (target->tap == NULL)
4717 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4718 e = JIM_ERR;
4721 if (e != JIM_OK) {
4722 free(target->type);
4723 free(target);
4724 return e;
4727 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4728 /* default endian to little if not specified */
4729 target->endianness = TARGET_LITTLE_ENDIAN;
4732 /* incase variant is not set */
4733 if (!target->variant)
4734 target->variant = strdup("");
4736 cp = Jim_GetString(new_cmd, NULL);
4737 target->cmd_name = strdup(cp);
4739 /* create the target specific commands */
4740 if (target->type->commands) {
4741 e = register_commands(cmd_ctx, NULL, target->type->commands);
4742 if (ERROR_OK != e)
4743 LOG_ERROR("unable to register '%s' commands", cp);
4745 if (target->type->target_create) {
4746 (*(target->type->target_create))(target, goi->interp);
4749 /* append to end of list */
4751 struct target **tpp;
4752 tpp = &(all_targets);
4753 while (*tpp) {
4754 tpp = &((*tpp)->next);
4756 *tpp = target;
4759 /* now - create the new target name command */
4760 const const struct command_registration target_subcommands[] = {
4762 .chain = target_instance_command_handlers,
4765 .chain = target->type->commands,
4767 COMMAND_REGISTRATION_DONE
4769 const const struct command_registration target_commands[] = {
4771 .name = cp,
4772 .mode = COMMAND_ANY,
4773 .help = "target command group",
4774 .chain = target_subcommands,
4776 COMMAND_REGISTRATION_DONE
4778 e = register_commands(cmd_ctx, NULL, target_commands);
4779 if (ERROR_OK != e)
4780 return JIM_ERR;
4782 struct command *c = command_find_in_context(cmd_ctx, cp);
4783 assert(c);
4784 command_set_handler_data(c, target);
4786 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4789 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4791 if (argc != 1)
4793 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4794 return JIM_ERR;
4796 struct command_context *cmd_ctx = current_command_context(interp);
4797 assert (cmd_ctx != NULL);
4799 Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4800 return JIM_OK;
4803 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4805 if (argc != 1)
4807 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4808 return JIM_ERR;
4810 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4811 for (unsigned x = 0; NULL != target_types[x]; x++)
4813 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4814 Jim_NewStringObj(interp, target_types[x]->name, -1));
4816 return JIM_OK;
4819 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4821 if (argc != 1)
4823 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4824 return JIM_ERR;
4826 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4827 struct target *target = all_targets;
4828 while (target)
4830 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4831 Jim_NewStringObj(interp, target_name(target), -1));
4832 target = target->next;
4834 return JIM_OK;
4837 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4839 Jim_GetOptInfo goi;
4840 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4841 if (goi.argc < 3)
4843 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4844 "<name> <target_type> [<target_options> ...]");
4845 return JIM_ERR;
4847 return target_create(&goi);
4850 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4852 Jim_GetOptInfo goi;
4853 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4855 /* It's OK to remove this mechanism sometime after August 2010 or so */
4856 LOG_WARNING("don't use numbers as target identifiers; use names");
4857 if (goi.argc != 1)
4859 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
4860 return JIM_ERR;
4862 jim_wide w;
4863 int e = Jim_GetOpt_Wide(&goi, &w);
4864 if (e != JIM_OK)
4865 return JIM_ERR;
4867 struct target *target;
4868 for (target = all_targets; NULL != target; target = target->next)
4870 if (target->target_number != w)
4871 continue;
4873 Jim_SetResultString(goi.interp, target_name(target), -1);
4874 return JIM_OK;
4877 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
4878 Jim_SetResultFormatted(goi.interp,
4879 "Target: number %#s does not exist", wObj);
4880 Jim_FreeNewObj(interp, wObj);
4882 return JIM_ERR;
4885 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4887 if (argc != 1)
4889 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4890 return JIM_ERR;
4892 unsigned count = 0;
4893 struct target *target = all_targets;
4894 while (NULL != target)
4896 target = target->next;
4897 count++;
4899 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4900 return JIM_OK;
4903 static const struct command_registration target_subcommand_handlers[] = {
4905 .name = "init",
4906 .mode = COMMAND_CONFIG,
4907 .handler = handle_target_init_command,
4908 .help = "initialize targets",
4911 .name = "create",
4912 /* REVISIT this should be COMMAND_CONFIG ... */
4913 .mode = COMMAND_ANY,
4914 .jim_handler = jim_target_create,
4915 .usage = "name type '-chain-position' name [options ...]",
4916 .help = "Creates and selects a new target",
4919 .name = "current",
4920 .mode = COMMAND_ANY,
4921 .jim_handler = jim_target_current,
4922 .help = "Returns the currently selected target",
4925 .name = "types",
4926 .mode = COMMAND_ANY,
4927 .jim_handler = jim_target_types,
4928 .help = "Returns the available target types as "
4929 "a list of strings",
4932 .name = "names",
4933 .mode = COMMAND_ANY,
4934 .jim_handler = jim_target_names,
4935 .help = "Returns the names of all targets as a list of strings",
4938 .name = "number",
4939 .mode = COMMAND_ANY,
4940 .jim_handler = jim_target_number,
4941 .usage = "number",
4942 .help = "Returns the name of the numbered target "
4943 "(DEPRECATED)",
4946 .name = "count",
4947 .mode = COMMAND_ANY,
4948 .jim_handler = jim_target_count,
4949 .help = "Returns the number of targets as an integer "
4950 "(DEPRECATED)",
4952 COMMAND_REGISTRATION_DONE
4955 struct FastLoad
4957 uint32_t address;
4958 uint8_t *data;
4959 int length;
4963 static int fastload_num;
4964 static struct FastLoad *fastload;
4966 static void free_fastload(void)
4968 if (fastload != NULL)
4970 int i;
4971 for (i = 0; i < fastload_num; i++)
4973 if (fastload[i].data)
4974 free(fastload[i].data);
4976 free(fastload);
4977 fastload = NULL;
4984 COMMAND_HANDLER(handle_fast_load_image_command)
4986 uint8_t *buffer;
4987 size_t buf_cnt;
4988 uint32_t image_size;
4989 uint32_t min_address = 0;
4990 uint32_t max_address = 0xffffffff;
4991 int i;
4993 struct image image;
4995 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4996 &image, &min_address, &max_address);
4997 if (ERROR_OK != retval)
4998 return retval;
5000 struct duration bench;
5001 duration_start(&bench);
5003 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5004 if (retval != ERROR_OK)
5006 return retval;
5009 image_size = 0x0;
5010 retval = ERROR_OK;
5011 fastload_num = image.num_sections;
5012 fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5013 if (fastload == NULL)
5015 command_print(CMD_CTX, "out of memory");
5016 image_close(&image);
5017 return ERROR_FAIL;
5019 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5020 for (i = 0; i < image.num_sections; i++)
5022 buffer = malloc(image.sections[i].size);
5023 if (buffer == NULL)
5025 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5026 (int)(image.sections[i].size));
5027 retval = ERROR_FAIL;
5028 break;
5031 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
5033 free(buffer);
5034 break;
5037 uint32_t offset = 0;
5038 uint32_t length = buf_cnt;
5041 /* DANGER!!! beware of unsigned comparision here!!! */
5043 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
5044 (image.sections[i].base_address < max_address))
5046 if (image.sections[i].base_address < min_address)
5048 /* clip addresses below */
5049 offset += min_address-image.sections[i].base_address;
5050 length -= offset;
5053 if (image.sections[i].base_address + buf_cnt > max_address)
5055 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5058 fastload[i].address = image.sections[i].base_address + offset;
5059 fastload[i].data = malloc(length);
5060 if (fastload[i].data == NULL)
5062 free(buffer);
5063 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5064 length);
5065 retval = ERROR_FAIL;
5066 break;
5068 memcpy(fastload[i].data, buffer + offset, length);
5069 fastload[i].length = length;
5071 image_size += length;
5072 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5073 (unsigned int)length,
5074 ((unsigned int)(image.sections[i].base_address + offset)));
5077 free(buffer);
5080 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5082 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5083 "in %fs (%0.3f KiB/s)", image_size,
5084 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5086 command_print(CMD_CTX,
5087 "WARNING: image has not been loaded to target!"
5088 "You can issue a 'fast_load' to finish loading.");
5091 image_close(&image);
5093 if (retval != ERROR_OK)
5095 free_fastload();
5098 return retval;
5101 COMMAND_HANDLER(handle_fast_load_command)
5103 if (CMD_ARGC > 0)
5104 return ERROR_COMMAND_SYNTAX_ERROR;
5105 if (fastload == NULL)
5107 LOG_ERROR("No image in memory");
5108 return ERROR_FAIL;
5110 int i;
5111 int ms = timeval_ms();
5112 int size = 0;
5113 int retval = ERROR_OK;
5114 for (i = 0; i < fastload_num;i++)
5116 struct target *target = get_current_target(CMD_CTX);
5117 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5118 (unsigned int)(fastload[i].address),
5119 (unsigned int)(fastload[i].length));
5120 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5121 if (retval != ERROR_OK)
5123 break;
5125 size += fastload[i].length;
5127 if (retval == ERROR_OK)
5129 int after = timeval_ms();
5130 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5132 return retval;
5135 static const struct command_registration target_command_handlers[] = {
5137 .name = "targets",
5138 .handler = handle_targets_command,
5139 .mode = COMMAND_ANY,
5140 .help = "change current default target (one parameter) "
5141 "or prints table of all targets (no parameters)",
5142 .usage = "[target]",
5145 .name = "target",
5146 .mode = COMMAND_CONFIG,
5147 .help = "configure target",
5149 .chain = target_subcommand_handlers,
5151 COMMAND_REGISTRATION_DONE
5154 int target_register_commands(struct command_context *cmd_ctx)
5156 return register_commands(cmd_ctx, NULL, target_command_handlers);
5159 static bool target_reset_nag = true;
5161 bool get_target_reset_nag(void)
5163 return target_reset_nag;
5166 COMMAND_HANDLER(handle_target_reset_nag)
5168 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5169 &target_reset_nag, "Nag after each reset about options to improve "
5170 "performance");
5173 static const struct command_registration target_exec_command_handlers[] = {
5175 .name = "fast_load_image",
5176 .handler = handle_fast_load_image_command,
5177 .mode = COMMAND_ANY,
5178 .help = "Load image into server memory for later use by "
5179 "fast_load; primarily for profiling",
5180 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5181 "[min_address [max_length]]",
5184 .name = "fast_load",
5185 .handler = handle_fast_load_command,
5186 .mode = COMMAND_EXEC,
5187 .help = "loads active fast load image to current target "
5188 "- mainly for profiling purposes",
5191 .name = "profile",
5192 .handler = handle_profile_command,
5193 .mode = COMMAND_EXEC,
5194 .help = "profiling samples the CPU PC",
5196 /** @todo don't register virt2phys() unless target supports it */
5198 .name = "virt2phys",
5199 .handler = handle_virt2phys_command,
5200 .mode = COMMAND_ANY,
5201 .help = "translate a virtual address into a physical address",
5202 .usage = "virtual_address",
5205 .name = "reg",
5206 .handler = handle_reg_command,
5207 .mode = COMMAND_EXEC,
5208 .help = "display or set a register; with no arguments, "
5209 "displays all registers and their values",
5210 .usage = "[(register_name|register_number) [value]]",
5213 .name = "poll",
5214 .handler = handle_poll_command,
5215 .mode = COMMAND_EXEC,
5216 .help = "poll target state; or reconfigure background polling",
5217 .usage = "['on'|'off']",
5220 .name = "wait_halt",
5221 .handler = handle_wait_halt_command,
5222 .mode = COMMAND_EXEC,
5223 .help = "wait up to the specified number of milliseconds "
5224 "(default 5) for a previously requested halt",
5225 .usage = "[milliseconds]",
5228 .name = "halt",
5229 .handler = handle_halt_command,
5230 .mode = COMMAND_EXEC,
5231 .help = "request target to halt, then wait up to the specified"
5232 "number of milliseconds (default 5) for it to complete",
5233 .usage = "[milliseconds]",
5236 .name = "resume",
5237 .handler = handle_resume_command,
5238 .mode = COMMAND_EXEC,
5239 .help = "resume target execution from current PC or address",
5240 .usage = "[address]",
5243 .name = "reset",
5244 .handler = handle_reset_command,
5245 .mode = COMMAND_EXEC,
5246 .usage = "[run|halt|init]",
5247 .help = "Reset all targets into the specified mode."
5248 "Default reset mode is run, if not given.",
5251 .name = "soft_reset_halt",
5252 .handler = handle_soft_reset_halt_command,
5253 .mode = COMMAND_EXEC,
5254 .help = "halt the target and do a soft reset",
5257 .name = "step",
5258 .handler = handle_step_command,
5259 .mode = COMMAND_EXEC,
5260 .help = "step one instruction from current PC or address",
5261 .usage = "[address]",
5264 .name = "mdw",
5265 .handler = handle_md_command,
5266 .mode = COMMAND_EXEC,
5267 .help = "display memory words",
5268 .usage = "['phys'] address [count]",
5271 .name = "mdh",
5272 .handler = handle_md_command,
5273 .mode = COMMAND_EXEC,
5274 .help = "display memory half-words",
5275 .usage = "['phys'] address [count]",
5278 .name = "mdb",
5279 .handler = handle_md_command,
5280 .mode = COMMAND_EXEC,
5281 .help = "display memory bytes",
5282 .usage = "['phys'] address [count]",
5285 .name = "mww",
5286 .handler = handle_mw_command,
5287 .mode = COMMAND_EXEC,
5288 .help = "write memory word",
5289 .usage = "['phys'] address value [count]",
5292 .name = "mwh",
5293 .handler = handle_mw_command,
5294 .mode = COMMAND_EXEC,
5295 .help = "write memory half-word",
5296 .usage = "['phys'] address value [count]",
5299 .name = "mwb",
5300 .handler = handle_mw_command,
5301 .mode = COMMAND_EXEC,
5302 .help = "write memory byte",
5303 .usage = "['phys'] address value [count]",
5306 .name = "bp",
5307 .handler = handle_bp_command,
5308 .mode = COMMAND_EXEC,
5309 .help = "list or set hardware or software breakpoint",
5310 .usage = "[address length ['hw']]",
5313 .name = "rbp",
5314 .handler = handle_rbp_command,
5315 .mode = COMMAND_EXEC,
5316 .help = "remove breakpoint",
5317 .usage = "address",
5320 .name = "wp",
5321 .handler = handle_wp_command,
5322 .mode = COMMAND_EXEC,
5323 .help = "list (no params) or create watchpoints",
5324 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5327 .name = "rwp",
5328 .handler = handle_rwp_command,
5329 .mode = COMMAND_EXEC,
5330 .help = "remove watchpoint",
5331 .usage = "address",
5334 .name = "load_image",
5335 .handler = handle_load_image_command,
5336 .mode = COMMAND_EXEC,
5337 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5338 "[min_address] [max_length]",
5341 .name = "dump_image",
5342 .handler = handle_dump_image_command,
5343 .mode = COMMAND_EXEC,
5344 .usage = "filename address size",
5347 .name = "verify_image",
5348 .handler = handle_verify_image_command,
5349 .mode = COMMAND_EXEC,
5350 .usage = "filename [offset [type]]",
5353 .name = "test_image",
5354 .handler = handle_test_image_command,
5355 .mode = COMMAND_EXEC,
5356 .usage = "filename [offset [type]]",
5359 .name = "mem2array",
5360 .mode = COMMAND_EXEC,
5361 .jim_handler = jim_mem2array,
5362 .help = "read 8/16/32 bit memory and return as a TCL array "
5363 "for script processing",
5364 .usage = "arrayname bitwidth address count",
5367 .name = "array2mem",
5368 .mode = COMMAND_EXEC,
5369 .jim_handler = jim_array2mem,
5370 .help = "convert a TCL array to memory locations "
5371 "and write the 8/16/32 bit values",
5372 .usage = "arrayname bitwidth address count",
5375 .name = "reset_nag",
5376 .handler = handle_target_reset_nag,
5377 .mode = COMMAND_ANY,
5378 .help = "Nag after each reset about options that could have been "
5379 "enabled to improve performance. ",
5380 .usage = "['enable'|'disable']",
5382 COMMAND_REGISTRATION_DONE
5384 static int target_register_user_commands(struct command_context *cmd_ctx)
5386 int retval = ERROR_OK;
5387 if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5388 return retval;
5390 if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5391 return retval;
5394 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);