1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
5 * Copyright (C) 2007-2010 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program; if not, write to the *
38 * Free Software Foundation, Inc., *
39 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
40 ***************************************************************************/
46 #include <helper/time_support.h>
47 #include <jtag/jtag.h>
48 #include <flash/nor/core.h>
51 #include "target_type.h"
52 #include "target_request.h"
53 #include "breakpoints.h"
57 #include "rtos/rtos.h"
58 #include "transport/transport.h"
60 /* default halt wait timeout (ms) */
61 #define DEFAULT_HALT_TIMEOUT 5000
63 static int target_read_buffer_default(struct target *target, uint32_t address,
64 uint32_t count, uint8_t *buffer);
65 static int target_write_buffer_default(struct target *target, uint32_t address,
66 uint32_t count, const uint8_t *buffer);
67 static int target_array2mem(Jim_Interp *interp, struct target *target,
68 int argc, Jim_Obj * const *argv);
69 static int target_mem2array(Jim_Interp *interp, struct target *target,
70 int argc, Jim_Obj * const *argv);
71 static int target_register_user_commands(struct command_context *cmd_ctx);
72 static int target_get_gdb_fileio_info_default(struct target *target,
73 struct gdb_fileio_info *fileio_info);
74 static int target_gdb_fileio_end_default(struct target *target, int retcode,
75 int fileio_errno, bool ctrl_c);
76 static int target_profiling_default(struct target *target, uint32_t *samples,
77 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
80 extern struct target_type arm7tdmi_target;
81 extern struct target_type arm720t_target;
82 extern struct target_type arm9tdmi_target;
83 extern struct target_type arm920t_target;
84 extern struct target_type arm966e_target;
85 extern struct target_type arm946e_target;
86 extern struct target_type arm926ejs_target;
87 extern struct target_type fa526_target;
88 extern struct target_type feroceon_target;
89 extern struct target_type dragonite_target;
90 extern struct target_type xscale_target;
91 extern struct target_type cortexm_target;
92 extern struct target_type cortexa_target;
93 extern struct target_type cortexr4_target;
94 extern struct target_type arm11_target;
95 extern struct target_type mips_m4k_target;
96 extern struct target_type avr_target;
97 extern struct target_type dsp563xx_target;
98 extern struct target_type dsp5680xx_target;
99 extern struct target_type testee_target;
100 extern struct target_type avr32_ap7k_target;
101 extern struct target_type hla_target;
102 extern struct target_type nds32_v2_target;
103 extern struct target_type nds32_v3_target;
104 extern struct target_type nds32_v3m_target;
105 extern struct target_type or1k_target;
106 extern struct target_type quark_x10xx_target;
108 static struct target_type *target_types[] = {
139 struct target *all_targets;
140 static struct target_event_callback *target_event_callbacks;
141 static struct target_timer_callback *target_timer_callbacks;
142 static const int polling_interval = 100;
144 static const Jim_Nvp nvp_assert[] = {
145 { .name = "assert", NVP_ASSERT },
146 { .name = "deassert", NVP_DEASSERT },
147 { .name = "T", NVP_ASSERT },
148 { .name = "F", NVP_DEASSERT },
149 { .name = "t", NVP_ASSERT },
150 { .name = "f", NVP_DEASSERT },
151 { .name = NULL, .value = -1 }
154 static const Jim_Nvp nvp_error_target[] = {
155 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
156 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
157 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
158 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
159 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
160 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
161 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
162 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
163 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
164 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
165 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
166 { .value = -1, .name = NULL }
169 static const char *target_strerror_safe(int err)
173 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
180 static const Jim_Nvp nvp_target_event[] = {
182 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
183 { .value = TARGET_EVENT_HALTED, .name = "halted" },
184 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
185 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
186 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
188 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
189 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
191 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
192 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
193 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
194 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
195 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
196 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
197 { .value = TARGET_EVENT_RESET_HALT_PRE, .name = "reset-halt-pre" },
198 { .value = TARGET_EVENT_RESET_HALT_POST, .name = "reset-halt-post" },
199 { .value = TARGET_EVENT_RESET_WAIT_PRE, .name = "reset-wait-pre" },
200 { .value = TARGET_EVENT_RESET_WAIT_POST, .name = "reset-wait-post" },
201 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
202 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
204 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
205 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
207 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
208 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
210 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
211 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
213 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
214 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
216 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
217 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
219 { .name = NULL, .value = -1 }
222 static const Jim_Nvp nvp_target_state[] = {
223 { .name = "unknown", .value = TARGET_UNKNOWN },
224 { .name = "running", .value = TARGET_RUNNING },
225 { .name = "halted", .value = TARGET_HALTED },
226 { .name = "reset", .value = TARGET_RESET },
227 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
228 { .name = NULL, .value = -1 },
231 static const Jim_Nvp nvp_target_debug_reason[] = {
232 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
233 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
234 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
235 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
236 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
237 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
238 { .name = "program-exit" , .value = DBG_REASON_EXIT },
239 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
240 { .name = NULL, .value = -1 },
243 static const Jim_Nvp nvp_target_endian[] = {
244 { .name = "big", .value = TARGET_BIG_ENDIAN },
245 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
246 { .name = "be", .value = TARGET_BIG_ENDIAN },
247 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
248 { .name = NULL, .value = -1 },
251 static const Jim_Nvp nvp_reset_modes[] = {
252 { .name = "unknown", .value = RESET_UNKNOWN },
253 { .name = "run" , .value = RESET_RUN },
254 { .name = "halt" , .value = RESET_HALT },
255 { .name = "init" , .value = RESET_INIT },
256 { .name = NULL , .value = -1 },
259 const char *debug_reason_name(struct target *t)
263 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
264 t->debug_reason)->name;
266 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
267 cp = "(*BUG*unknown*BUG*)";
272 const char *target_state_name(struct target *t)
275 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
277 LOG_ERROR("Invalid target state: %d", (int)(t->state));
278 cp = "(*BUG*unknown*BUG*)";
283 /* determine the number of the new target */
284 static int new_target_number(void)
289 /* number is 0 based */
293 if (x < t->target_number)
294 x = t->target_number;
300 /* read a uint64_t from a buffer in target memory endianness */
301 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
303 if (target->endianness == TARGET_LITTLE_ENDIAN)
304 return le_to_h_u64(buffer);
306 return be_to_h_u64(buffer);
309 /* read a uint32_t from a buffer in target memory endianness */
310 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
312 if (target->endianness == TARGET_LITTLE_ENDIAN)
313 return le_to_h_u32(buffer);
315 return be_to_h_u32(buffer);
318 /* read a uint24_t from a buffer in target memory endianness */
319 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
321 if (target->endianness == TARGET_LITTLE_ENDIAN)
322 return le_to_h_u24(buffer);
324 return be_to_h_u24(buffer);
327 /* read a uint16_t from a buffer in target memory endianness */
328 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
330 if (target->endianness == TARGET_LITTLE_ENDIAN)
331 return le_to_h_u16(buffer);
333 return be_to_h_u16(buffer);
336 /* read a uint8_t from a buffer in target memory endianness */
337 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
339 return *buffer & 0x0ff;
342 /* write a uint64_t to a buffer in target memory endianness */
343 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
345 if (target->endianness == TARGET_LITTLE_ENDIAN)
346 h_u64_to_le(buffer, value);
348 h_u64_to_be(buffer, value);
351 /* write a uint32_t to a buffer in target memory endianness */
352 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
354 if (target->endianness == TARGET_LITTLE_ENDIAN)
355 h_u32_to_le(buffer, value);
357 h_u32_to_be(buffer, value);
360 /* write a uint24_t to a buffer in target memory endianness */
361 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
363 if (target->endianness == TARGET_LITTLE_ENDIAN)
364 h_u24_to_le(buffer, value);
366 h_u24_to_be(buffer, value);
369 /* write a uint16_t to a buffer in target memory endianness */
370 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
372 if (target->endianness == TARGET_LITTLE_ENDIAN)
373 h_u16_to_le(buffer, value);
375 h_u16_to_be(buffer, value);
378 /* write a uint8_t to a buffer in target memory endianness */
379 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
384 /* write a uint64_t array to a buffer in target memory endianness */
385 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
388 for (i = 0; i < count; i++)
389 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
392 /* write a uint32_t array to a buffer in target memory endianness */
393 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
396 for (i = 0; i < count; i++)
397 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
400 /* write a uint16_t array to a buffer in target memory endianness */
401 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
404 for (i = 0; i < count; i++)
405 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
408 /* write a uint64_t array to a buffer in target memory endianness */
409 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
412 for (i = 0; i < count; i++)
413 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
416 /* write a uint32_t array to a buffer in target memory endianness */
417 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
420 for (i = 0; i < count; i++)
421 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
424 /* write a uint16_t array to a buffer in target memory endianness */
425 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
428 for (i = 0; i < count; i++)
429 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
432 /* return a pointer to a configured target; id is name or number */
433 struct target *get_target(const char *id)
435 struct target *target;
437 /* try as tcltarget name */
438 for (target = all_targets; target; target = target->next) {
439 if (target_name(target) == NULL)
441 if (strcmp(id, target_name(target)) == 0)
445 /* It's OK to remove this fallback sometime after August 2010 or so */
447 /* no match, try as number */
449 if (parse_uint(id, &num) != ERROR_OK)
452 for (target = all_targets; target; target = target->next) {
453 if (target->target_number == (int)num) {
454 LOG_WARNING("use '%s' as target identifier, not '%u'",
455 target_name(target), num);
463 /* returns a pointer to the n-th configured target */
464 static struct target *get_target_by_num(int num)
466 struct target *target = all_targets;
469 if (target->target_number == num)
471 target = target->next;
477 struct target *get_current_target(struct command_context *cmd_ctx)
479 struct target *target = get_target_by_num(cmd_ctx->current_target);
481 if (target == NULL) {
482 LOG_ERROR("BUG: current_target out of bounds");
489 int target_poll(struct target *target)
493 /* We can't poll until after examine */
494 if (!target_was_examined(target)) {
495 /* Fail silently lest we pollute the log */
499 retval = target->type->poll(target);
500 if (retval != ERROR_OK)
503 if (target->halt_issued) {
504 if (target->state == TARGET_HALTED)
505 target->halt_issued = false;
507 long long t = timeval_ms() - target->halt_issued_time;
508 if (t > DEFAULT_HALT_TIMEOUT) {
509 target->halt_issued = false;
510 LOG_INFO("Halt timed out, wake up GDB.");
511 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
519 int target_halt(struct target *target)
522 /* We can't poll until after examine */
523 if (!target_was_examined(target)) {
524 LOG_ERROR("Target not examined yet");
528 retval = target->type->halt(target);
529 if (retval != ERROR_OK)
532 target->halt_issued = true;
533 target->halt_issued_time = timeval_ms();
539 * Make the target (re)start executing using its saved execution
540 * context (possibly with some modifications).
542 * @param target Which target should start executing.
543 * @param current True to use the target's saved program counter instead
544 * of the address parameter
545 * @param address Optionally used as the program counter.
546 * @param handle_breakpoints True iff breakpoints at the resumption PC
547 * should be skipped. (For example, maybe execution was stopped by
548 * such a breakpoint, in which case it would be counterprodutive to
550 * @param debug_execution False if all working areas allocated by OpenOCD
551 * should be released and/or restored to their original contents.
552 * (This would for example be true to run some downloaded "helper"
553 * algorithm code, which resides in one such working buffer and uses
554 * another for data storage.)
556 * @todo Resolve the ambiguity about what the "debug_execution" flag
557 * signifies. For example, Target implementations don't agree on how
558 * it relates to invalidation of the register cache, or to whether
559 * breakpoints and watchpoints should be enabled. (It would seem wrong
560 * to enable breakpoints when running downloaded "helper" algorithms
561 * (debug_execution true), since the breakpoints would be set to match
562 * target firmware being debugged, not the helper algorithm.... and
563 * enabling them could cause such helpers to malfunction (for example,
564 * by overwriting data with a breakpoint instruction. On the other
565 * hand the infrastructure for running such helpers might use this
566 * procedure but rely on hardware breakpoint to detect termination.)
568 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
572 /* We can't poll until after examine */
573 if (!target_was_examined(target)) {
574 LOG_ERROR("Target not examined yet");
578 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
580 /* note that resume *must* be asynchronous. The CPU can halt before
581 * we poll. The CPU can even halt at the current PC as a result of
582 * a software breakpoint being inserted by (a bug?) the application.
584 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
585 if (retval != ERROR_OK)
588 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
593 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
598 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
599 if (n->name == NULL) {
600 LOG_ERROR("invalid reset mode");
604 /* disable polling during reset to make reset event scripts
605 * more predictable, i.e. dr/irscan & pathmove in events will
606 * not have JTAG operations injected into the middle of a sequence.
608 bool save_poll = jtag_poll_get_enabled();
610 jtag_poll_set_enabled(false);
612 sprintf(buf, "ocd_process_reset %s", n->name);
613 retval = Jim_Eval(cmd_ctx->interp, buf);
615 jtag_poll_set_enabled(save_poll);
617 if (retval != JIM_OK) {
618 Jim_MakeErrorMessage(cmd_ctx->interp);
619 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
623 /* We want any events to be processed before the prompt */
624 retval = target_call_timer_callbacks_now();
626 struct target *target;
627 for (target = all_targets; target; target = target->next) {
628 target->type->check_reset(target);
629 target->running_alg = false;
635 static int identity_virt2phys(struct target *target,
636 uint32_t virtual, uint32_t *physical)
642 static int no_mmu(struct target *target, int *enabled)
648 static int default_examine(struct target *target)
650 target_set_examined(target);
654 /* no check by default */
655 static int default_check_reset(struct target *target)
660 int target_examine_one(struct target *target)
662 return target->type->examine(target);
665 static int jtag_enable_callback(enum jtag_event event, void *priv)
667 struct target *target = priv;
669 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
672 jtag_unregister_event_callback(jtag_enable_callback, target);
674 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
676 int retval = target_examine_one(target);
677 if (retval != ERROR_OK)
680 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
685 /* Targets that correctly implement init + examine, i.e.
686 * no communication with target during init:
690 int target_examine(void)
692 int retval = ERROR_OK;
693 struct target *target;
695 for (target = all_targets; target; target = target->next) {
696 /* defer examination, but don't skip it */
697 if (!target->tap->enabled) {
698 jtag_register_event_callback(jtag_enable_callback,
703 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
705 retval = target_examine_one(target);
706 if (retval != ERROR_OK)
709 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
714 const char *target_type_name(struct target *target)
716 return target->type->name;
719 static int target_soft_reset_halt(struct target *target)
721 if (!target_was_examined(target)) {
722 LOG_ERROR("Target not examined yet");
725 if (!target->type->soft_reset_halt) {
726 LOG_ERROR("Target %s does not support soft_reset_halt",
727 target_name(target));
730 return target->type->soft_reset_halt(target);
734 * Downloads a target-specific native code algorithm to the target,
735 * and executes it. * Note that some targets may need to set up, enable,
736 * and tear down a breakpoint (hard or * soft) to detect algorithm
737 * termination, while others may support lower overhead schemes where
738 * soft breakpoints embedded in the algorithm automatically terminate the
741 * @param target used to run the algorithm
742 * @param arch_info target-specific description of the algorithm.
744 int target_run_algorithm(struct target *target,
745 int num_mem_params, struct mem_param *mem_params,
746 int num_reg_params, struct reg_param *reg_param,
747 uint32_t entry_point, uint32_t exit_point,
748 int timeout_ms, void *arch_info)
750 int retval = ERROR_FAIL;
752 if (!target_was_examined(target)) {
753 LOG_ERROR("Target not examined yet");
756 if (!target->type->run_algorithm) {
757 LOG_ERROR("Target type '%s' does not support %s",
758 target_type_name(target), __func__);
762 target->running_alg = true;
763 retval = target->type->run_algorithm(target,
764 num_mem_params, mem_params,
765 num_reg_params, reg_param,
766 entry_point, exit_point, timeout_ms, arch_info);
767 target->running_alg = false;
774 * Downloads a target-specific native code algorithm to the target,
775 * executes and leaves it running.
777 * @param target used to run the algorithm
778 * @param arch_info target-specific description of the algorithm.
780 int target_start_algorithm(struct target *target,
781 int num_mem_params, struct mem_param *mem_params,
782 int num_reg_params, struct reg_param *reg_params,
783 uint32_t entry_point, uint32_t exit_point,
786 int retval = ERROR_FAIL;
788 if (!target_was_examined(target)) {
789 LOG_ERROR("Target not examined yet");
792 if (!target->type->start_algorithm) {
793 LOG_ERROR("Target type '%s' does not support %s",
794 target_type_name(target), __func__);
797 if (target->running_alg) {
798 LOG_ERROR("Target is already running an algorithm");
802 target->running_alg = true;
803 retval = target->type->start_algorithm(target,
804 num_mem_params, mem_params,
805 num_reg_params, reg_params,
806 entry_point, exit_point, arch_info);
813 * Waits for an algorithm started with target_start_algorithm() to complete.
815 * @param target used to run the algorithm
816 * @param arch_info target-specific description of the algorithm.
818 int target_wait_algorithm(struct target *target,
819 int num_mem_params, struct mem_param *mem_params,
820 int num_reg_params, struct reg_param *reg_params,
821 uint32_t exit_point, int timeout_ms,
824 int retval = ERROR_FAIL;
826 if (!target->type->wait_algorithm) {
827 LOG_ERROR("Target type '%s' does not support %s",
828 target_type_name(target), __func__);
831 if (!target->running_alg) {
832 LOG_ERROR("Target is not running an algorithm");
836 retval = target->type->wait_algorithm(target,
837 num_mem_params, mem_params,
838 num_reg_params, reg_params,
839 exit_point, timeout_ms, arch_info);
840 if (retval != ERROR_TARGET_TIMEOUT)
841 target->running_alg = false;
848 * Executes a target-specific native code algorithm in the target.
849 * It differs from target_run_algorithm in that the algorithm is asynchronous.
850 * Because of this it requires an compliant algorithm:
851 * see contrib/loaders/flash/stm32f1x.S for example.
853 * @param target used to run the algorithm
856 int target_run_flash_async_algorithm(struct target *target,
857 const uint8_t *buffer, uint32_t count, int block_size,
858 int num_mem_params, struct mem_param *mem_params,
859 int num_reg_params, struct reg_param *reg_params,
860 uint32_t buffer_start, uint32_t buffer_size,
861 uint32_t entry_point, uint32_t exit_point, void *arch_info)
866 const uint8_t *buffer_orig = buffer;
868 /* Set up working area. First word is write pointer, second word is read pointer,
869 * rest is fifo data area. */
870 uint32_t wp_addr = buffer_start;
871 uint32_t rp_addr = buffer_start + 4;
872 uint32_t fifo_start_addr = buffer_start + 8;
873 uint32_t fifo_end_addr = buffer_start + buffer_size;
875 uint32_t wp = fifo_start_addr;
876 uint32_t rp = fifo_start_addr;
878 /* validate block_size is 2^n */
879 assert(!block_size || !(block_size & (block_size - 1)));
881 retval = target_write_u32(target, wp_addr, wp);
882 if (retval != ERROR_OK)
884 retval = target_write_u32(target, rp_addr, rp);
885 if (retval != ERROR_OK)
888 /* Start up algorithm on target and let it idle while writing the first chunk */
889 retval = target_start_algorithm(target, num_mem_params, mem_params,
890 num_reg_params, reg_params,
895 if (retval != ERROR_OK) {
896 LOG_ERROR("error starting target flash write algorithm");
902 retval = target_read_u32(target, rp_addr, &rp);
903 if (retval != ERROR_OK) {
904 LOG_ERROR("failed to get read pointer");
908 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
909 (buffer - buffer_orig), count, wp, rp);
912 LOG_ERROR("flash write algorithm aborted by target");
913 retval = ERROR_FLASH_OPERATION_FAILED;
917 if ((rp & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
918 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
922 /* Count the number of bytes available in the fifo without
923 * crossing the wrap around. Make sure to not fill it completely,
924 * because that would make wp == rp and that's the empty condition. */
925 uint32_t thisrun_bytes;
927 thisrun_bytes = rp - wp - block_size;
928 else if (rp > fifo_start_addr)
929 thisrun_bytes = fifo_end_addr - wp;
931 thisrun_bytes = fifo_end_addr - wp - block_size;
933 if (thisrun_bytes == 0) {
934 /* Throttle polling a bit if transfer is (much) faster than flash
935 * programming. The exact delay shouldn't matter as long as it's
936 * less than buffer size / flash speed. This is very unlikely to
937 * run when using high latency connections such as USB. */
940 /* to stop an infinite loop on some targets check and increment a timeout
941 * this issue was observed on a stellaris using the new ICDI interface */
942 if (timeout++ >= 500) {
943 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
944 return ERROR_FLASH_OPERATION_FAILED;
949 /* reset our timeout */
952 /* Limit to the amount of data we actually want to write */
953 if (thisrun_bytes > count * block_size)
954 thisrun_bytes = count * block_size;
956 /* Write data to fifo */
957 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
958 if (retval != ERROR_OK)
961 /* Update counters and wrap write pointer */
962 buffer += thisrun_bytes;
963 count -= thisrun_bytes / block_size;
965 if (wp >= fifo_end_addr)
966 wp = fifo_start_addr;
968 /* Store updated write pointer to target */
969 retval = target_write_u32(target, wp_addr, wp);
970 if (retval != ERROR_OK)
974 if (retval != ERROR_OK) {
975 /* abort flash write algorithm on target */
976 target_write_u32(target, wp_addr, 0);
979 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
980 num_reg_params, reg_params,
985 if (retval2 != ERROR_OK) {
986 LOG_ERROR("error waiting for target flash write algorithm");
993 int target_read_memory(struct target *target,
994 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
996 if (!target_was_examined(target)) {
997 LOG_ERROR("Target not examined yet");
1000 return target->type->read_memory(target, address, size, count, buffer);
1003 int target_read_phys_memory(struct target *target,
1004 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1006 if (!target_was_examined(target)) {
1007 LOG_ERROR("Target not examined yet");
1010 return target->type->read_phys_memory(target, address, size, count, buffer);
1013 int target_write_memory(struct target *target,
1014 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1016 if (!target_was_examined(target)) {
1017 LOG_ERROR("Target not examined yet");
1020 return target->type->write_memory(target, address, size, count, buffer);
1023 int target_write_phys_memory(struct target *target,
1024 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1026 if (!target_was_examined(target)) {
1027 LOG_ERROR("Target not examined yet");
1030 return target->type->write_phys_memory(target, address, size, count, buffer);
1033 int target_add_breakpoint(struct target *target,
1034 struct breakpoint *breakpoint)
1036 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1037 LOG_WARNING("target %s is not halted", target_name(target));
1038 return ERROR_TARGET_NOT_HALTED;
1040 return target->type->add_breakpoint(target, breakpoint);
1043 int target_add_context_breakpoint(struct target *target,
1044 struct breakpoint *breakpoint)
1046 if (target->state != TARGET_HALTED) {
1047 LOG_WARNING("target %s is not halted", target_name(target));
1048 return ERROR_TARGET_NOT_HALTED;
1050 return target->type->add_context_breakpoint(target, breakpoint);
1053 int target_add_hybrid_breakpoint(struct target *target,
1054 struct breakpoint *breakpoint)
1056 if (target->state != TARGET_HALTED) {
1057 LOG_WARNING("target %s is not halted", target_name(target));
1058 return ERROR_TARGET_NOT_HALTED;
1060 return target->type->add_hybrid_breakpoint(target, breakpoint);
1063 int target_remove_breakpoint(struct target *target,
1064 struct breakpoint *breakpoint)
1066 return target->type->remove_breakpoint(target, breakpoint);
1069 int target_add_watchpoint(struct target *target,
1070 struct watchpoint *watchpoint)
1072 if (target->state != TARGET_HALTED) {
1073 LOG_WARNING("target %s is not halted", target_name(target));
1074 return ERROR_TARGET_NOT_HALTED;
1076 return target->type->add_watchpoint(target, watchpoint);
1078 int target_remove_watchpoint(struct target *target,
1079 struct watchpoint *watchpoint)
1081 return target->type->remove_watchpoint(target, watchpoint);
1083 int target_hit_watchpoint(struct target *target,
1084 struct watchpoint **hit_watchpoint)
1086 if (target->state != TARGET_HALTED) {
1087 LOG_WARNING("target %s is not halted", target->cmd_name);
1088 return ERROR_TARGET_NOT_HALTED;
1091 if (target->type->hit_watchpoint == NULL) {
1092 /* For backward compatible, if hit_watchpoint is not implemented,
1093 * return ERROR_FAIL such that gdb_server will not take the nonsense
1098 return target->type->hit_watchpoint(target, hit_watchpoint);
1101 int target_get_gdb_reg_list(struct target *target,
1102 struct reg **reg_list[], int *reg_list_size,
1103 enum target_register_class reg_class)
1105 return target->type->get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1107 int target_step(struct target *target,
1108 int current, uint32_t address, int handle_breakpoints)
1110 return target->type->step(target, current, address, handle_breakpoints);
1113 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1115 if (target->state != TARGET_HALTED) {
1116 LOG_WARNING("target %s is not halted", target->cmd_name);
1117 return ERROR_TARGET_NOT_HALTED;
1119 return target->type->get_gdb_fileio_info(target, fileio_info);
1122 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1124 if (target->state != TARGET_HALTED) {
1125 LOG_WARNING("target %s is not halted", target->cmd_name);
1126 return ERROR_TARGET_NOT_HALTED;
1128 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1131 int target_profiling(struct target *target, uint32_t *samples,
1132 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1134 if (target->state != TARGET_HALTED) {
1135 LOG_WARNING("target %s is not halted", target->cmd_name);
1136 return ERROR_TARGET_NOT_HALTED;
1138 return target->type->profiling(target, samples, max_num_samples,
1139 num_samples, seconds);
1143 * Reset the @c examined flag for the given target.
1144 * Pure paranoia -- targets are zeroed on allocation.
1146 static void target_reset_examined(struct target *target)
1148 target->examined = false;
1151 static int err_read_phys_memory(struct target *target, uint32_t address,
1152 uint32_t size, uint32_t count, uint8_t *buffer)
1154 LOG_ERROR("Not implemented: %s", __func__);
1158 static int err_write_phys_memory(struct target *target, uint32_t address,
1159 uint32_t size, uint32_t count, const uint8_t *buffer)
1161 LOG_ERROR("Not implemented: %s", __func__);
1165 static int handle_target(void *priv);
1167 static int target_init_one(struct command_context *cmd_ctx,
1168 struct target *target)
1170 target_reset_examined(target);
1172 struct target_type *type = target->type;
1173 if (type->examine == NULL)
1174 type->examine = default_examine;
1176 if (type->check_reset == NULL)
1177 type->check_reset = default_check_reset;
1179 assert(type->init_target != NULL);
1181 int retval = type->init_target(cmd_ctx, target);
1182 if (ERROR_OK != retval) {
1183 LOG_ERROR("target '%s' init failed", target_name(target));
1187 /* Sanity-check MMU support ... stub in what we must, to help
1188 * implement it in stages, but warn if we need to do so.
1191 if (type->write_phys_memory == NULL) {
1192 LOG_ERROR("type '%s' is missing write_phys_memory",
1194 type->write_phys_memory = err_write_phys_memory;
1196 if (type->read_phys_memory == NULL) {
1197 LOG_ERROR("type '%s' is missing read_phys_memory",
1199 type->read_phys_memory = err_read_phys_memory;
1201 if (type->virt2phys == NULL) {
1202 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1203 type->virt2phys = identity_virt2phys;
1206 /* Make sure no-MMU targets all behave the same: make no
1207 * distinction between physical and virtual addresses, and
1208 * ensure that virt2phys() is always an identity mapping.
1210 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1211 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1214 type->write_phys_memory = type->write_memory;
1215 type->read_phys_memory = type->read_memory;
1216 type->virt2phys = identity_virt2phys;
1219 if (target->type->read_buffer == NULL)
1220 target->type->read_buffer = target_read_buffer_default;
1222 if (target->type->write_buffer == NULL)
1223 target->type->write_buffer = target_write_buffer_default;
1225 if (target->type->get_gdb_fileio_info == NULL)
1226 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1228 if (target->type->gdb_fileio_end == NULL)
1229 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1231 if (target->type->profiling == NULL)
1232 target->type->profiling = target_profiling_default;
1237 static int target_init(struct command_context *cmd_ctx)
1239 struct target *target;
1242 for (target = all_targets; target; target = target->next) {
1243 retval = target_init_one(cmd_ctx, target);
1244 if (ERROR_OK != retval)
1251 retval = target_register_user_commands(cmd_ctx);
1252 if (ERROR_OK != retval)
1255 retval = target_register_timer_callback(&handle_target,
1256 polling_interval, 1, cmd_ctx->interp);
1257 if (ERROR_OK != retval)
1263 COMMAND_HANDLER(handle_target_init_command)
1268 return ERROR_COMMAND_SYNTAX_ERROR;
1270 static bool target_initialized;
1271 if (target_initialized) {
1272 LOG_INFO("'target init' has already been called");
1275 target_initialized = true;
1277 retval = command_run_line(CMD_CTX, "init_targets");
1278 if (ERROR_OK != retval)
1281 retval = command_run_line(CMD_CTX, "init_target_events");
1282 if (ERROR_OK != retval)
1285 retval = command_run_line(CMD_CTX, "init_board");
1286 if (ERROR_OK != retval)
1289 LOG_DEBUG("Initializing targets...");
1290 return target_init(CMD_CTX);
1293 int target_register_event_callback(int (*callback)(struct target *target,
1294 enum target_event event, void *priv), void *priv)
1296 struct target_event_callback **callbacks_p = &target_event_callbacks;
1298 if (callback == NULL)
1299 return ERROR_COMMAND_SYNTAX_ERROR;
1302 while ((*callbacks_p)->next)
1303 callbacks_p = &((*callbacks_p)->next);
1304 callbacks_p = &((*callbacks_p)->next);
1307 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1308 (*callbacks_p)->callback = callback;
1309 (*callbacks_p)->priv = priv;
1310 (*callbacks_p)->next = NULL;
1315 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
1317 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1320 if (callback == NULL)
1321 return ERROR_COMMAND_SYNTAX_ERROR;
1324 while ((*callbacks_p)->next)
1325 callbacks_p = &((*callbacks_p)->next);
1326 callbacks_p = &((*callbacks_p)->next);
1329 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1330 (*callbacks_p)->callback = callback;
1331 (*callbacks_p)->periodic = periodic;
1332 (*callbacks_p)->time_ms = time_ms;
1334 gettimeofday(&now, NULL);
1335 (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
1336 time_ms -= (time_ms % 1000);
1337 (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
1338 if ((*callbacks_p)->when.tv_usec > 1000000) {
1339 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
1340 (*callbacks_p)->when.tv_sec += 1;
1343 (*callbacks_p)->priv = priv;
1344 (*callbacks_p)->next = NULL;
1349 int target_unregister_event_callback(int (*callback)(struct target *target,
1350 enum target_event event, void *priv), void *priv)
1352 struct target_event_callback **p = &target_event_callbacks;
1353 struct target_event_callback *c = target_event_callbacks;
1355 if (callback == NULL)
1356 return ERROR_COMMAND_SYNTAX_ERROR;
1359 struct target_event_callback *next = c->next;
1360 if ((c->callback == callback) && (c->priv == priv)) {
1372 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1374 struct target_timer_callback **p = &target_timer_callbacks;
1375 struct target_timer_callback *c = target_timer_callbacks;
1377 if (callback == NULL)
1378 return ERROR_COMMAND_SYNTAX_ERROR;
1381 struct target_timer_callback *next = c->next;
1382 if ((c->callback == callback) && (c->priv == priv)) {
1394 int target_call_event_callbacks(struct target *target, enum target_event event)
1396 struct target_event_callback *callback = target_event_callbacks;
1397 struct target_event_callback *next_callback;
1399 if (event == TARGET_EVENT_HALTED) {
1400 /* execute early halted first */
1401 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1404 LOG_DEBUG("target event %i (%s)", event,
1405 Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1407 target_handle_event(target, event);
1410 next_callback = callback->next;
1411 callback->callback(target, event, callback->priv);
1412 callback = next_callback;
1418 static int target_timer_callback_periodic_restart(
1419 struct target_timer_callback *cb, struct timeval *now)
1421 int time_ms = cb->time_ms;
1422 cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1423 time_ms -= (time_ms % 1000);
1424 cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1425 if (cb->when.tv_usec > 1000000) {
1426 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1427 cb->when.tv_sec += 1;
1432 static int target_call_timer_callback(struct target_timer_callback *cb,
1433 struct timeval *now)
1435 cb->callback(cb->priv);
1438 return target_timer_callback_periodic_restart(cb, now);
1440 return target_unregister_timer_callback(cb->callback, cb->priv);
1443 static int target_call_timer_callbacks_check_time(int checktime)
1448 gettimeofday(&now, NULL);
1450 struct target_timer_callback *callback = target_timer_callbacks;
1452 /* cleaning up may unregister and free this callback */
1453 struct target_timer_callback *next_callback = callback->next;
1455 bool call_it = callback->callback &&
1456 ((!checktime && callback->periodic) ||
1457 now.tv_sec > callback->when.tv_sec ||
1458 (now.tv_sec == callback->when.tv_sec &&
1459 now.tv_usec >= callback->when.tv_usec));
1462 int retval = target_call_timer_callback(callback, &now);
1463 if (retval != ERROR_OK)
1467 callback = next_callback;
1473 int target_call_timer_callbacks(void)
1475 return target_call_timer_callbacks_check_time(1);
1478 /* invoke periodic callbacks immediately */
1479 int target_call_timer_callbacks_now(void)
1481 return target_call_timer_callbacks_check_time(0);
1484 /* Prints the working area layout for debug purposes */
1485 static void print_wa_layout(struct target *target)
1487 struct working_area *c = target->working_areas;
1490 LOG_DEBUG("%c%c 0x%08"PRIx32"-0x%08"PRIx32" (%"PRIu32" bytes)",
1491 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1492 c->address, c->address + c->size - 1, c->size);
1497 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1498 static void target_split_working_area(struct working_area *area, uint32_t size)
1500 assert(area->free); /* Shouldn't split an allocated area */
1501 assert(size <= area->size); /* Caller should guarantee this */
1503 /* Split only if not already the right size */
1504 if (size < area->size) {
1505 struct working_area *new_wa = malloc(sizeof(*new_wa));
1510 new_wa->next = area->next;
1511 new_wa->size = area->size - size;
1512 new_wa->address = area->address + size;
1513 new_wa->backup = NULL;
1514 new_wa->user = NULL;
1515 new_wa->free = true;
1517 area->next = new_wa;
1520 /* If backup memory was allocated to this area, it has the wrong size
1521 * now so free it and it will be reallocated if/when needed */
1524 area->backup = NULL;
1529 /* Merge all adjacent free areas into one */
1530 static void target_merge_working_areas(struct target *target)
1532 struct working_area *c = target->working_areas;
1534 while (c && c->next) {
1535 assert(c->next->address == c->address + c->size); /* This is an invariant */
1537 /* Find two adjacent free areas */
1538 if (c->free && c->next->free) {
1539 /* Merge the last into the first */
1540 c->size += c->next->size;
1542 /* Remove the last */
1543 struct working_area *to_be_freed = c->next;
1544 c->next = c->next->next;
1545 if (to_be_freed->backup)
1546 free(to_be_freed->backup);
1549 /* If backup memory was allocated to the remaining area, it's has
1550 * the wrong size now */
1561 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1563 /* Reevaluate working area address based on MMU state*/
1564 if (target->working_areas == NULL) {
1568 retval = target->type->mmu(target, &enabled);
1569 if (retval != ERROR_OK)
1573 if (target->working_area_phys_spec) {
1574 LOG_DEBUG("MMU disabled, using physical "
1575 "address for working memory 0x%08"PRIx32,
1576 target->working_area_phys);
1577 target->working_area = target->working_area_phys;
1579 LOG_ERROR("No working memory available. "
1580 "Specify -work-area-phys to target.");
1581 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1584 if (target->working_area_virt_spec) {
1585 LOG_DEBUG("MMU enabled, using virtual "
1586 "address for working memory 0x%08"PRIx32,
1587 target->working_area_virt);
1588 target->working_area = target->working_area_virt;
1590 LOG_ERROR("No working memory available. "
1591 "Specify -work-area-virt to target.");
1592 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1596 /* Set up initial working area on first call */
1597 struct working_area *new_wa = malloc(sizeof(*new_wa));
1599 new_wa->next = NULL;
1600 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1601 new_wa->address = target->working_area;
1602 new_wa->backup = NULL;
1603 new_wa->user = NULL;
1604 new_wa->free = true;
1607 target->working_areas = new_wa;
1610 /* only allocate multiples of 4 byte */
1612 size = (size + 3) & (~3UL);
1614 struct working_area *c = target->working_areas;
1616 /* Find the first large enough working area */
1618 if (c->free && c->size >= size)
1624 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1626 /* Split the working area into the requested size */
1627 target_split_working_area(c, size);
1629 LOG_DEBUG("allocated new working area of %"PRIu32" bytes at address 0x%08"PRIx32, size, c->address);
1631 if (target->backup_working_area) {
1632 if (c->backup == NULL) {
1633 c->backup = malloc(c->size);
1634 if (c->backup == NULL)
1638 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1639 if (retval != ERROR_OK)
1643 /* mark as used, and return the new (reused) area */
1650 print_wa_layout(target);
1655 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1659 retval = target_alloc_working_area_try(target, size, area);
1660 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1661 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1666 static int target_restore_working_area(struct target *target, struct working_area *area)
1668 int retval = ERROR_OK;
1670 if (target->backup_working_area && area->backup != NULL) {
1671 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1672 if (retval != ERROR_OK)
1673 LOG_ERROR("failed to restore %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1674 area->size, area->address);
1680 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1681 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1683 int retval = ERROR_OK;
1689 retval = target_restore_working_area(target, area);
1690 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1691 if (retval != ERROR_OK)
1697 LOG_DEBUG("freed %"PRIu32" bytes of working area at address 0x%08"PRIx32,
1698 area->size, area->address);
1700 /* mark user pointer invalid */
1701 /* TODO: Is this really safe? It points to some previous caller's memory.
1702 * How could we know that the area pointer is still in that place and not
1703 * some other vital data? What's the purpose of this, anyway? */
1707 target_merge_working_areas(target);
1709 print_wa_layout(target);
1714 int target_free_working_area(struct target *target, struct working_area *area)
1716 return target_free_working_area_restore(target, area, 1);
1719 /* free resources and restore memory, if restoring memory fails,
1720 * free up resources anyway
1722 static void target_free_all_working_areas_restore(struct target *target, int restore)
1724 struct working_area *c = target->working_areas;
1726 LOG_DEBUG("freeing all working areas");
1728 /* Loop through all areas, restoring the allocated ones and marking them as free */
1732 target_restore_working_area(target, c);
1734 *c->user = NULL; /* Same as above */
1740 /* Run a merge pass to combine all areas into one */
1741 target_merge_working_areas(target);
1743 print_wa_layout(target);
1746 void target_free_all_working_areas(struct target *target)
1748 target_free_all_working_areas_restore(target, 1);
1751 /* Find the largest number of bytes that can be allocated */
1752 uint32_t target_get_working_area_avail(struct target *target)
1754 struct working_area *c = target->working_areas;
1755 uint32_t max_size = 0;
1758 return target->working_area_size;
1761 if (c->free && max_size < c->size)
1770 int target_arch_state(struct target *target)
1773 if (target == NULL) {
1774 LOG_USER("No target has been configured");
1778 LOG_USER("target state: %s", target_state_name(target));
1780 if (target->state != TARGET_HALTED)
1783 retval = target->type->arch_state(target);
1787 static int target_get_gdb_fileio_info_default(struct target *target,
1788 struct gdb_fileio_info *fileio_info)
1790 /* If target does not support semi-hosting function, target
1791 has no need to provide .get_gdb_fileio_info callback.
1792 It just return ERROR_FAIL and gdb_server will return "Txx"
1793 as target halted every time. */
1797 static int target_gdb_fileio_end_default(struct target *target,
1798 int retcode, int fileio_errno, bool ctrl_c)
1803 static int target_profiling_default(struct target *target, uint32_t *samples,
1804 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1806 struct timeval timeout, now;
1808 gettimeofday(&timeout, NULL);
1809 timeval_add_time(&timeout, seconds, 0);
1811 LOG_INFO("Starting profiling. Halting and resuming the"
1812 " target as often as we can...");
1814 uint32_t sample_count = 0;
1815 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
1816 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
1818 int retval = ERROR_OK;
1820 target_poll(target);
1821 if (target->state == TARGET_HALTED) {
1822 uint32_t t = *((uint32_t *)reg->value);
1823 samples[sample_count++] = t;
1824 /* current pc, addr = 0, do not handle breakpoints, not debugging */
1825 retval = target_resume(target, 1, 0, 0, 0);
1826 target_poll(target);
1827 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
1828 } else if (target->state == TARGET_RUNNING) {
1829 /* We want to quickly sample the PC. */
1830 retval = target_halt(target);
1832 LOG_INFO("Target not halted or running");
1837 if (retval != ERROR_OK)
1840 gettimeofday(&now, NULL);
1841 if ((sample_count >= max_num_samples) ||
1842 ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec))) {
1843 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
1848 *num_samples = sample_count;
1852 /* Single aligned words are guaranteed to use 16 or 32 bit access
1853 * mode respectively, otherwise data is handled as quickly as
1856 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1858 LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1859 (int)size, (unsigned)address);
1861 if (!target_was_examined(target)) {
1862 LOG_ERROR("Target not examined yet");
1869 if ((address + size - 1) < address) {
1870 /* GDB can request this when e.g. PC is 0xfffffffc*/
1871 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1877 return target->type->write_buffer(target, address, size, buffer);
1880 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t count, const uint8_t *buffer)
1884 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1885 * will have something to do with the size we leave to it. */
1886 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1887 if (address & size) {
1888 int retval = target_write_memory(target, address, size, 1, buffer);
1889 if (retval != ERROR_OK)
1897 /* Write the data with as large access size as possible. */
1898 for (; size > 0; size /= 2) {
1899 uint32_t aligned = count - count % size;
1901 int retval = target_write_memory(target, address, size, aligned / size, buffer);
1902 if (retval != ERROR_OK)
1913 /* Single aligned words are guaranteed to use 16 or 32 bit access
1914 * mode respectively, otherwise data is handled as quickly as
1917 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1919 LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1920 (int)size, (unsigned)address);
1922 if (!target_was_examined(target)) {
1923 LOG_ERROR("Target not examined yet");
1930 if ((address + size - 1) < address) {
1931 /* GDB can request this when e.g. PC is 0xfffffffc*/
1932 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1938 return target->type->read_buffer(target, address, size, buffer);
1941 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t count, uint8_t *buffer)
1945 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
1946 * will have something to do with the size we leave to it. */
1947 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
1948 if (address & size) {
1949 int retval = target_read_memory(target, address, size, 1, buffer);
1950 if (retval != ERROR_OK)
1958 /* Read the data with as large access size as possible. */
1959 for (; size > 0; size /= 2) {
1960 uint32_t aligned = count - count % size;
1962 int retval = target_read_memory(target, address, size, aligned / size, buffer);
1963 if (retval != ERROR_OK)
1974 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1979 uint32_t checksum = 0;
1980 if (!target_was_examined(target)) {
1981 LOG_ERROR("Target not examined yet");
1985 retval = target->type->checksum_memory(target, address, size, &checksum);
1986 if (retval != ERROR_OK) {
1987 buffer = malloc(size);
1988 if (buffer == NULL) {
1989 LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1990 return ERROR_COMMAND_SYNTAX_ERROR;
1992 retval = target_read_buffer(target, address, size, buffer);
1993 if (retval != ERROR_OK) {
1998 /* convert to target endianness */
1999 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2000 uint32_t target_data;
2001 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2002 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2005 retval = image_calculate_checksum(buffer, size, &checksum);
2014 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
2017 if (!target_was_examined(target)) {
2018 LOG_ERROR("Target not examined yet");
2022 if (target->type->blank_check_memory == 0)
2023 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2025 retval = target->type->blank_check_memory(target, address, size, blank);
2030 int target_read_u64(struct target *target, uint64_t address, uint64_t *value)
2032 uint8_t value_buf[8];
2033 if (!target_was_examined(target)) {
2034 LOG_ERROR("Target not examined yet");
2038 int retval = target_read_memory(target, address, 8, 1, value_buf);
2040 if (retval == ERROR_OK) {
2041 *value = target_buffer_get_u64(target, value_buf);
2042 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2047 LOG_DEBUG("address: 0x%" PRIx64 " failed",
2054 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
2056 uint8_t value_buf[4];
2057 if (!target_was_examined(target)) {
2058 LOG_ERROR("Target not examined yet");
2062 int retval = target_read_memory(target, address, 4, 1, value_buf);
2064 if (retval == ERROR_OK) {
2065 *value = target_buffer_get_u32(target, value_buf);
2066 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2071 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2078 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
2080 uint8_t value_buf[2];
2081 if (!target_was_examined(target)) {
2082 LOG_ERROR("Target not examined yet");
2086 int retval = target_read_memory(target, address, 2, 1, value_buf);
2088 if (retval == ERROR_OK) {
2089 *value = target_buffer_get_u16(target, value_buf);
2090 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
2095 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2102 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
2104 if (!target_was_examined(target)) {
2105 LOG_ERROR("Target not examined yet");
2109 int retval = target_read_memory(target, address, 1, 1, value);
2111 if (retval == ERROR_OK) {
2112 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2117 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
2124 int target_write_u64(struct target *target, uint64_t address, uint64_t value)
2127 uint8_t value_buf[8];
2128 if (!target_was_examined(target)) {
2129 LOG_ERROR("Target not examined yet");
2133 LOG_DEBUG("address: 0x%" PRIx64 ", value: 0x%16.16" PRIx64 "",
2137 target_buffer_set_u64(target, value_buf, value);
2138 retval = target_write_memory(target, address, 8, 1, value_buf);
2139 if (retval != ERROR_OK)
2140 LOG_DEBUG("failed: %i", retval);
2145 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
2148 uint8_t value_buf[4];
2149 if (!target_was_examined(target)) {
2150 LOG_ERROR("Target not examined yet");
2154 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
2158 target_buffer_set_u32(target, value_buf, value);
2159 retval = target_write_memory(target, address, 4, 1, value_buf);
2160 if (retval != ERROR_OK)
2161 LOG_DEBUG("failed: %i", retval);
2166 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
2169 uint8_t value_buf[2];
2170 if (!target_was_examined(target)) {
2171 LOG_ERROR("Target not examined yet");
2175 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
2179 target_buffer_set_u16(target, value_buf, value);
2180 retval = target_write_memory(target, address, 2, 1, value_buf);
2181 if (retval != ERROR_OK)
2182 LOG_DEBUG("failed: %i", retval);
2187 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
2190 if (!target_was_examined(target)) {
2191 LOG_ERROR("Target not examined yet");
2195 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
2198 retval = target_write_memory(target, address, 1, 1, &value);
2199 if (retval != ERROR_OK)
2200 LOG_DEBUG("failed: %i", retval);
2205 static int find_target(struct command_context *cmd_ctx, const char *name)
2207 struct target *target = get_target(name);
2208 if (target == NULL) {
2209 LOG_ERROR("Target: %s is unknown, try one of:\n", name);
2212 if (!target->tap->enabled) {
2213 LOG_USER("Target: TAP %s is disabled, "
2214 "can't be the current target\n",
2215 target->tap->dotted_name);
2219 cmd_ctx->current_target = target->target_number;
2224 COMMAND_HANDLER(handle_targets_command)
2226 int retval = ERROR_OK;
2227 if (CMD_ARGC == 1) {
2228 retval = find_target(CMD_CTX, CMD_ARGV[0]);
2229 if (retval == ERROR_OK) {
2235 struct target *target = all_targets;
2236 command_print(CMD_CTX, " TargetName Type Endian TapName State ");
2237 command_print(CMD_CTX, "-- ------------------ ---------- ------ ------------------ ------------");
2242 if (target->tap->enabled)
2243 state = target_state_name(target);
2245 state = "tap-disabled";
2247 if (CMD_CTX->current_target == target->target_number)
2250 /* keep columns lined up to match the headers above */
2251 command_print(CMD_CTX,
2252 "%2d%c %-18s %-10s %-6s %-18s %s",
2253 target->target_number,
2255 target_name(target),
2256 target_type_name(target),
2257 Jim_Nvp_value2name_simple(nvp_target_endian,
2258 target->endianness)->name,
2259 target->tap->dotted_name,
2261 target = target->next;
2267 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2269 static int powerDropout;
2270 static int srstAsserted;
2272 static int runPowerRestore;
2273 static int runPowerDropout;
2274 static int runSrstAsserted;
2275 static int runSrstDeasserted;
2277 static int sense_handler(void)
2279 static int prevSrstAsserted;
2280 static int prevPowerdropout;
2282 int retval = jtag_power_dropout(&powerDropout);
2283 if (retval != ERROR_OK)
2287 powerRestored = prevPowerdropout && !powerDropout;
2289 runPowerRestore = 1;
2291 long long current = timeval_ms();
2292 static long long lastPower;
2293 int waitMore = lastPower + 2000 > current;
2294 if (powerDropout && !waitMore) {
2295 runPowerDropout = 1;
2296 lastPower = current;
2299 retval = jtag_srst_asserted(&srstAsserted);
2300 if (retval != ERROR_OK)
2304 srstDeasserted = prevSrstAsserted && !srstAsserted;
2306 static long long lastSrst;
2307 waitMore = lastSrst + 2000 > current;
2308 if (srstDeasserted && !waitMore) {
2309 runSrstDeasserted = 1;
2313 if (!prevSrstAsserted && srstAsserted)
2314 runSrstAsserted = 1;
2316 prevSrstAsserted = srstAsserted;
2317 prevPowerdropout = powerDropout;
2319 if (srstDeasserted || powerRestored) {
2320 /* Other than logging the event we can't do anything here.
2321 * Issuing a reset is a particularly bad idea as we might
2322 * be inside a reset already.
2329 /* process target state changes */
2330 static int handle_target(void *priv)
2332 Jim_Interp *interp = (Jim_Interp *)priv;
2333 int retval = ERROR_OK;
2335 if (!is_jtag_poll_safe()) {
2336 /* polling is disabled currently */
2340 /* we do not want to recurse here... */
2341 static int recursive;
2345 /* danger! running these procedures can trigger srst assertions and power dropouts.
2346 * We need to avoid an infinite loop/recursion here and we do that by
2347 * clearing the flags after running these events.
2349 int did_something = 0;
2350 if (runSrstAsserted) {
2351 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2352 Jim_Eval(interp, "srst_asserted");
2355 if (runSrstDeasserted) {
2356 Jim_Eval(interp, "srst_deasserted");
2359 if (runPowerDropout) {
2360 LOG_INFO("Power dropout detected, running power_dropout proc.");
2361 Jim_Eval(interp, "power_dropout");
2364 if (runPowerRestore) {
2365 Jim_Eval(interp, "power_restore");
2369 if (did_something) {
2370 /* clear detect flags */
2374 /* clear action flags */
2376 runSrstAsserted = 0;
2377 runSrstDeasserted = 0;
2378 runPowerRestore = 0;
2379 runPowerDropout = 0;
2384 /* Poll targets for state changes unless that's globally disabled.
2385 * Skip targets that are currently disabled.
2387 for (struct target *target = all_targets;
2388 is_jtag_poll_safe() && target;
2389 target = target->next) {
2391 if (!target_was_examined(target))
2394 if (!target->tap->enabled)
2397 if (target->backoff.times > target->backoff.count) {
2398 /* do not poll this time as we failed previously */
2399 target->backoff.count++;
2402 target->backoff.count = 0;
2404 /* only poll target if we've got power and srst isn't asserted */
2405 if (!powerDropout && !srstAsserted) {
2406 /* polling may fail silently until the target has been examined */
2407 retval = target_poll(target);
2408 if (retval != ERROR_OK) {
2409 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2410 if (target->backoff.times * polling_interval < 5000) {
2411 target->backoff.times *= 2;
2412 target->backoff.times++;
2414 LOG_USER("Polling target %s failed, GDB will be halted. Polling again in %dms",
2415 target_name(target),
2416 target->backoff.times * polling_interval);
2418 /* Tell GDB to halt the debugger. This allows the user to
2419 * run monitor commands to handle the situation.
2421 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2424 /* Since we succeeded, we reset backoff count */
2425 if (target->backoff.times > 0) {
2426 LOG_USER("Polling target %s succeeded again, trying to reexamine", target_name(target));
2427 target_reset_examined(target);
2428 target_examine_one(target);
2431 target->backoff.times = 0;
2438 COMMAND_HANDLER(handle_reg_command)
2440 struct target *target;
2441 struct reg *reg = NULL;
2447 target = get_current_target(CMD_CTX);
2449 /* list all available registers for the current target */
2450 if (CMD_ARGC == 0) {
2451 struct reg_cache *cache = target->reg_cache;
2457 command_print(CMD_CTX, "===== %s", cache->name);
2459 for (i = 0, reg = cache->reg_list;
2460 i < cache->num_regs;
2461 i++, reg++, count++) {
2462 /* only print cached values if they are valid */
2464 value = buf_to_str(reg->value,
2466 command_print(CMD_CTX,
2467 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2475 command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2480 cache = cache->next;
2486 /* access a single register by its ordinal number */
2487 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2489 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2491 struct reg_cache *cache = target->reg_cache;
2495 for (i = 0; i < cache->num_regs; i++) {
2496 if (count++ == num) {
2497 reg = &cache->reg_list[i];
2503 cache = cache->next;
2507 command_print(CMD_CTX, "%i is out of bounds, the current target "
2508 "has only %i registers (0 - %i)", num, count, count - 1);
2512 /* access a single register by its name */
2513 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2516 command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2521 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2523 /* display a register */
2524 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2525 && (CMD_ARGV[1][0] <= '9')))) {
2526 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2529 if (reg->valid == 0)
2530 reg->type->get(reg);
2531 value = buf_to_str(reg->value, reg->size, 16);
2532 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2537 /* set register value */
2538 if (CMD_ARGC == 2) {
2539 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2542 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2544 reg->type->set(reg, buf);
2546 value = buf_to_str(reg->value, reg->size, 16);
2547 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2555 return ERROR_COMMAND_SYNTAX_ERROR;
2558 COMMAND_HANDLER(handle_poll_command)
2560 int retval = ERROR_OK;
2561 struct target *target = get_current_target(CMD_CTX);
2563 if (CMD_ARGC == 0) {
2564 command_print(CMD_CTX, "background polling: %s",
2565 jtag_poll_get_enabled() ? "on" : "off");
2566 command_print(CMD_CTX, "TAP: %s (%s)",
2567 target->tap->dotted_name,
2568 target->tap->enabled ? "enabled" : "disabled");
2569 if (!target->tap->enabled)
2571 retval = target_poll(target);
2572 if (retval != ERROR_OK)
2574 retval = target_arch_state(target);
2575 if (retval != ERROR_OK)
2577 } else if (CMD_ARGC == 1) {
2579 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2580 jtag_poll_set_enabled(enable);
2582 return ERROR_COMMAND_SYNTAX_ERROR;
2587 COMMAND_HANDLER(handle_wait_halt_command)
2590 return ERROR_COMMAND_SYNTAX_ERROR;
2592 unsigned ms = DEFAULT_HALT_TIMEOUT;
2593 if (1 == CMD_ARGC) {
2594 int retval = parse_uint(CMD_ARGV[0], &ms);
2595 if (ERROR_OK != retval)
2596 return ERROR_COMMAND_SYNTAX_ERROR;
2599 struct target *target = get_current_target(CMD_CTX);
2600 return target_wait_state(target, TARGET_HALTED, ms);
2603 /* wait for target state to change. The trick here is to have a low
2604 * latency for short waits and not to suck up all the CPU time
2607 * After 500ms, keep_alive() is invoked
2609 int target_wait_state(struct target *target, enum target_state state, int ms)
2612 long long then = 0, cur;
2616 retval = target_poll(target);
2617 if (retval != ERROR_OK)
2619 if (target->state == state)
2624 then = timeval_ms();
2625 LOG_DEBUG("waiting for target %s...",
2626 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2632 if ((cur-then) > ms) {
2633 LOG_ERROR("timed out while waiting for target %s",
2634 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
2642 COMMAND_HANDLER(handle_halt_command)
2646 struct target *target = get_current_target(CMD_CTX);
2647 int retval = target_halt(target);
2648 if (ERROR_OK != retval)
2651 if (CMD_ARGC == 1) {
2652 unsigned wait_local;
2653 retval = parse_uint(CMD_ARGV[0], &wait_local);
2654 if (ERROR_OK != retval)
2655 return ERROR_COMMAND_SYNTAX_ERROR;
2660 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2663 COMMAND_HANDLER(handle_soft_reset_halt_command)
2665 struct target *target = get_current_target(CMD_CTX);
2667 LOG_USER("requesting target halt and executing a soft reset");
2669 target_soft_reset_halt(target);
2674 COMMAND_HANDLER(handle_reset_command)
2677 return ERROR_COMMAND_SYNTAX_ERROR;
2679 enum target_reset_mode reset_mode = RESET_RUN;
2680 if (CMD_ARGC == 1) {
2682 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2683 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
2684 return ERROR_COMMAND_SYNTAX_ERROR;
2685 reset_mode = n->value;
2688 /* reset *all* targets */
2689 return target_process_reset(CMD_CTX, reset_mode);
2693 COMMAND_HANDLER(handle_resume_command)
2697 return ERROR_COMMAND_SYNTAX_ERROR;
2699 struct target *target = get_current_target(CMD_CTX);
2701 /* with no CMD_ARGV, resume from current pc, addr = 0,
2702 * with one arguments, addr = CMD_ARGV[0],
2703 * handle breakpoints, not debugging */
2705 if (CMD_ARGC == 1) {
2706 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2710 return target_resume(target, current, addr, 1, 0);
2713 COMMAND_HANDLER(handle_step_command)
2716 return ERROR_COMMAND_SYNTAX_ERROR;
2720 /* with no CMD_ARGV, step from current pc, addr = 0,
2721 * with one argument addr = CMD_ARGV[0],
2722 * handle breakpoints, debugging */
2725 if (CMD_ARGC == 1) {
2726 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2730 struct target *target = get_current_target(CMD_CTX);
2732 return target->type->step(target, current_pc, addr, 1);
2735 static void handle_md_output(struct command_context *cmd_ctx,
2736 struct target *target, uint32_t address, unsigned size,
2737 unsigned count, const uint8_t *buffer)
2739 const unsigned line_bytecnt = 32;
2740 unsigned line_modulo = line_bytecnt / size;
2742 char output[line_bytecnt * 4 + 1];
2743 unsigned output_len = 0;
2745 const char *value_fmt;
2748 value_fmt = "%8.8x ";
2751 value_fmt = "%4.4x ";
2754 value_fmt = "%2.2x ";
2757 /* "can't happen", caller checked */
2758 LOG_ERROR("invalid memory read size: %u", size);
2762 for (unsigned i = 0; i < count; i++) {
2763 if (i % line_modulo == 0) {
2764 output_len += snprintf(output + output_len,
2765 sizeof(output) - output_len,
2767 (unsigned)(address + (i*size)));
2771 const uint8_t *value_ptr = buffer + i * size;
2774 value = target_buffer_get_u32(target, value_ptr);
2777 value = target_buffer_get_u16(target, value_ptr);
2782 output_len += snprintf(output + output_len,
2783 sizeof(output) - output_len,
2786 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
2787 command_print(cmd_ctx, "%s", output);
2793 COMMAND_HANDLER(handle_md_command)
2796 return ERROR_COMMAND_SYNTAX_ERROR;
2799 switch (CMD_NAME[2]) {
2810 return ERROR_COMMAND_SYNTAX_ERROR;
2813 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2814 int (*fn)(struct target *target,
2815 uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2819 fn = target_read_phys_memory;
2821 fn = target_read_memory;
2822 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2823 return ERROR_COMMAND_SYNTAX_ERROR;
2826 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2830 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2832 uint8_t *buffer = calloc(count, size);
2834 struct target *target = get_current_target(CMD_CTX);
2835 int retval = fn(target, address, size, count, buffer);
2836 if (ERROR_OK == retval)
2837 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2844 typedef int (*target_write_fn)(struct target *target,
2845 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2847 static int target_fill_mem(struct target *target,
2856 /* We have to write in reasonably large chunks to be able
2857 * to fill large memory areas with any sane speed */
2858 const unsigned chunk_size = 16384;
2859 uint8_t *target_buf = malloc(chunk_size * data_size);
2860 if (target_buf == NULL) {
2861 LOG_ERROR("Out of memory");
2865 for (unsigned i = 0; i < chunk_size; i++) {
2866 switch (data_size) {
2868 target_buffer_set_u32(target, target_buf + i * data_size, b);
2871 target_buffer_set_u16(target, target_buf + i * data_size, b);
2874 target_buffer_set_u8(target, target_buf + i * data_size, b);
2881 int retval = ERROR_OK;
2883 for (unsigned x = 0; x < c; x += chunk_size) {
2886 if (current > chunk_size)
2887 current = chunk_size;
2888 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2889 if (retval != ERROR_OK)
2891 /* avoid GDB timeouts */
2900 COMMAND_HANDLER(handle_mw_command)
2903 return ERROR_COMMAND_SYNTAX_ERROR;
2904 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
2909 fn = target_write_phys_memory;
2911 fn = target_write_memory;
2912 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2913 return ERROR_COMMAND_SYNTAX_ERROR;
2916 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2919 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2923 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2925 struct target *target = get_current_target(CMD_CTX);
2927 switch (CMD_NAME[2]) {
2938 return ERROR_COMMAND_SYNTAX_ERROR;
2941 return target_fill_mem(target, address, fn, wordsize, value, count);
2944 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2945 uint32_t *min_address, uint32_t *max_address)
2947 if (CMD_ARGC < 1 || CMD_ARGC > 5)
2948 return ERROR_COMMAND_SYNTAX_ERROR;
2950 /* a base address isn't always necessary,
2951 * default to 0x0 (i.e. don't relocate) */
2952 if (CMD_ARGC >= 2) {
2954 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2955 image->base_address = addr;
2956 image->base_address_set = 1;
2958 image->base_address_set = 0;
2960 image->start_address_set = 0;
2963 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2964 if (CMD_ARGC == 5) {
2965 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2966 /* use size (given) to find max (required) */
2967 *max_address += *min_address;
2970 if (*min_address > *max_address)
2971 return ERROR_COMMAND_SYNTAX_ERROR;
2976 COMMAND_HANDLER(handle_load_image_command)
2980 uint32_t image_size;
2981 uint32_t min_address = 0;
2982 uint32_t max_address = 0xffffffff;
2986 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2987 &image, &min_address, &max_address);
2988 if (ERROR_OK != retval)
2991 struct target *target = get_current_target(CMD_CTX);
2993 struct duration bench;
2994 duration_start(&bench);
2996 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3001 for (i = 0; i < image.num_sections; i++) {
3002 buffer = malloc(image.sections[i].size);
3003 if (buffer == NULL) {
3004 command_print(CMD_CTX,
3005 "error allocating buffer for section (%d bytes)",
3006 (int)(image.sections[i].size));
3010 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3011 if (retval != ERROR_OK) {
3016 uint32_t offset = 0;
3017 uint32_t length = buf_cnt;
3019 /* DANGER!!! beware of unsigned comparision here!!! */
3021 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3022 (image.sections[i].base_address < max_address)) {
3024 if (image.sections[i].base_address < min_address) {
3025 /* clip addresses below */
3026 offset += min_address-image.sections[i].base_address;
3030 if (image.sections[i].base_address + buf_cnt > max_address)
3031 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3033 retval = target_write_buffer(target,
3034 image.sections[i].base_address + offset, length, buffer + offset);
3035 if (retval != ERROR_OK) {
3039 image_size += length;
3040 command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
3041 (unsigned int)length,
3042 image.sections[i].base_address + offset);
3048 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3049 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
3050 "in %fs (%0.3f KiB/s)", image_size,
3051 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3054 image_close(&image);
3060 COMMAND_HANDLER(handle_dump_image_command)
3062 struct fileio fileio;
3064 int retval, retvaltemp;
3065 uint32_t address, size;
3066 struct duration bench;
3067 struct target *target = get_current_target(CMD_CTX);
3070 return ERROR_COMMAND_SYNTAX_ERROR;
3072 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
3073 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
3075 uint32_t buf_size = (size > 4096) ? 4096 : size;
3076 buffer = malloc(buf_size);
3080 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3081 if (retval != ERROR_OK) {
3086 duration_start(&bench);
3089 size_t size_written;
3090 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3091 retval = target_read_buffer(target, address, this_run_size, buffer);
3092 if (retval != ERROR_OK)
3095 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
3096 if (retval != ERROR_OK)
3099 size -= this_run_size;
3100 address += this_run_size;
3105 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3107 retval = fileio_size(&fileio, &filesize);
3108 if (retval != ERROR_OK)
3110 command_print(CMD_CTX,
3111 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
3112 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3115 retvaltemp = fileio_close(&fileio);
3116 if (retvaltemp != ERROR_OK)
3122 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
3126 uint32_t image_size;
3129 uint32_t checksum = 0;
3130 uint32_t mem_checksum = 0;
3134 struct target *target = get_current_target(CMD_CTX);
3137 return ERROR_COMMAND_SYNTAX_ERROR;
3140 LOG_ERROR("no target selected");
3144 struct duration bench;
3145 duration_start(&bench);
3147 if (CMD_ARGC >= 2) {
3149 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
3150 image.base_address = addr;
3151 image.base_address_set = 1;
3153 image.base_address_set = 0;
3154 image.base_address = 0x0;
3157 image.start_address_set = 0;
3159 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3160 if (retval != ERROR_OK)
3166 for (i = 0; i < image.num_sections; i++) {
3167 buffer = malloc(image.sections[i].size);
3168 if (buffer == NULL) {
3169 command_print(CMD_CTX,
3170 "error allocating buffer for section (%d bytes)",
3171 (int)(image.sections[i].size));
3174 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3175 if (retval != ERROR_OK) {
3181 /* calculate checksum of image */
3182 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3183 if (retval != ERROR_OK) {
3188 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3189 if (retval != ERROR_OK) {
3194 if (checksum != mem_checksum) {
3195 /* failed crc checksum, fall back to a binary compare */
3199 LOG_ERROR("checksum mismatch - attempting binary compare");
3201 data = malloc(buf_cnt);
3203 /* Can we use 32bit word accesses? */
3205 int count = buf_cnt;
3206 if ((count % 4) == 0) {
3210 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3211 if (retval == ERROR_OK) {
3213 for (t = 0; t < buf_cnt; t++) {
3214 if (data[t] != buffer[t]) {
3215 command_print(CMD_CTX,
3216 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3218 (unsigned)(t + image.sections[i].base_address),
3221 if (diffs++ >= 127) {
3222 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
3234 command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
3235 image.sections[i].base_address,
3240 image_size += buf_cnt;
3243 command_print(CMD_CTX, "No more differences found.");
3246 retval = ERROR_FAIL;
3247 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3248 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
3249 "in %fs (%0.3f KiB/s)", image_size,
3250 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3253 image_close(&image);
3258 COMMAND_HANDLER(handle_verify_image_command)
3260 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
3263 COMMAND_HANDLER(handle_test_image_command)
3265 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
3268 static int handle_bp_command_list(struct command_context *cmd_ctx)
3270 struct target *target = get_current_target(cmd_ctx);
3271 struct breakpoint *breakpoint = target->breakpoints;
3272 while (breakpoint) {
3273 if (breakpoint->type == BKPT_SOFT) {
3274 char *buf = buf_to_str(breakpoint->orig_instr,
3275 breakpoint->length, 16);
3276 command_print(cmd_ctx, "IVA breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
3277 breakpoint->address,
3279 breakpoint->set, buf);
3282 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3283 command_print(cmd_ctx, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3285 breakpoint->length, breakpoint->set);
3286 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3287 command_print(cmd_ctx, "Hybrid breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3288 breakpoint->address,
3289 breakpoint->length, breakpoint->set);
3290 command_print(cmd_ctx, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3293 command_print(cmd_ctx, "Breakpoint(IVA): 0x%8.8" PRIx32 ", 0x%x, %i",
3294 breakpoint->address,
3295 breakpoint->length, breakpoint->set);
3298 breakpoint = breakpoint->next;
3303 static int handle_bp_command_set(struct command_context *cmd_ctx,
3304 uint32_t addr, uint32_t asid, uint32_t length, int hw)
3306 struct target *target = get_current_target(cmd_ctx);
3309 int retval = breakpoint_add(target, addr, length, hw);
3310 if (ERROR_OK == retval)
3311 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
3313 LOG_ERROR("Failure setting breakpoint, the same address(IVA) is already used");
3316 } else if (addr == 0) {
3317 int retval = context_breakpoint_add(target, asid, length, hw);
3318 if (ERROR_OK == retval)
3319 command_print(cmd_ctx, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3321 LOG_ERROR("Failure setting breakpoint, the same address(CONTEXTID) is already used");
3325 int retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3326 if (ERROR_OK == retval)
3327 command_print(cmd_ctx, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3329 LOG_ERROR("Failure setting breakpoint, the same address is already used");
3336 COMMAND_HANDLER(handle_bp_command)
3345 return handle_bp_command_list(CMD_CTX);
3349 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3350 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3351 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3354 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3356 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3358 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3361 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3362 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3364 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3365 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3367 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3372 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3373 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3374 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3375 return handle_bp_command_set(CMD_CTX, addr, asid, length, hw);
3378 return ERROR_COMMAND_SYNTAX_ERROR;
3382 COMMAND_HANDLER(handle_rbp_command)
3385 return ERROR_COMMAND_SYNTAX_ERROR;
3388 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3390 struct target *target = get_current_target(CMD_CTX);
3391 breakpoint_remove(target, addr);
3396 COMMAND_HANDLER(handle_wp_command)
3398 struct target *target = get_current_target(CMD_CTX);
3400 if (CMD_ARGC == 0) {
3401 struct watchpoint *watchpoint = target->watchpoints;
3403 while (watchpoint) {
3404 command_print(CMD_CTX, "address: 0x%8.8" PRIx32
3405 ", len: 0x%8.8" PRIx32
3406 ", r/w/a: %i, value: 0x%8.8" PRIx32
3407 ", mask: 0x%8.8" PRIx32,
3408 watchpoint->address,
3410 (int)watchpoint->rw,
3413 watchpoint = watchpoint->next;
3418 enum watchpoint_rw type = WPT_ACCESS;
3420 uint32_t length = 0;
3421 uint32_t data_value = 0x0;
3422 uint32_t data_mask = 0xffffffff;
3426 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3429 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3432 switch (CMD_ARGV[2][0]) {
3443 LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3444 return ERROR_COMMAND_SYNTAX_ERROR;
3448 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3449 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3453 return ERROR_COMMAND_SYNTAX_ERROR;
3456 int retval = watchpoint_add(target, addr, length, type,
3457 data_value, data_mask);
3458 if (ERROR_OK != retval)
3459 LOG_ERROR("Failure setting watchpoints");
3464 COMMAND_HANDLER(handle_rwp_command)
3467 return ERROR_COMMAND_SYNTAX_ERROR;
3470 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3472 struct target *target = get_current_target(CMD_CTX);
3473 watchpoint_remove(target, addr);
3479 * Translate a virtual address to a physical address.
3481 * The low-level target implementation must have logged a detailed error
3482 * which is forwarded to telnet/GDB session.
3484 COMMAND_HANDLER(handle_virt2phys_command)
3487 return ERROR_COMMAND_SYNTAX_ERROR;
3490 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3493 struct target *target = get_current_target(CMD_CTX);
3494 int retval = target->type->virt2phys(target, va, &pa);
3495 if (retval == ERROR_OK)
3496 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3501 static void writeData(FILE *f, const void *data, size_t len)
3503 size_t written = fwrite(data, 1, len, f);
3505 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3508 static void writeLong(FILE *f, int l)
3511 for (i = 0; i < 4; i++) {
3512 char c = (l >> (i*8))&0xff;
3513 writeData(f, &c, 1);
3518 static void writeString(FILE *f, char *s)
3520 writeData(f, s, strlen(s));
3523 typedef unsigned char UNIT[2]; /* unit of profiling */
3525 /* Dump a gmon.out histogram file. */
3526 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename,
3527 bool with_range, uint32_t start_address, uint32_t end_address)
3530 FILE *f = fopen(filename, "w");
3533 writeString(f, "gmon");
3534 writeLong(f, 0x00000001); /* Version */
3535 writeLong(f, 0); /* padding */
3536 writeLong(f, 0); /* padding */
3537 writeLong(f, 0); /* padding */
3539 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
3540 writeData(f, &zero, 1);
3542 /* figure out bucket size */
3546 min = start_address;
3551 for (i = 0; i < sampleNum; i++) {
3552 if (min > samples[i])
3554 if (max < samples[i])
3558 /* max should be (largest sample + 1)
3559 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3563 int addressSpace = max - min;
3564 assert(addressSpace >= 2);
3566 /* FIXME: What is the reasonable number of buckets?
3567 * The profiling result will be more accurate if there are enough buckets. */
3568 static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
3569 uint32_t numBuckets = addressSpace / sizeof(UNIT);
3570 if (numBuckets > maxBuckets)
3571 numBuckets = maxBuckets;
3572 int *buckets = malloc(sizeof(int) * numBuckets);
3573 if (buckets == NULL) {
3577 memset(buckets, 0, sizeof(int) * numBuckets);
3578 for (i = 0; i < sampleNum; i++) {
3579 uint32_t address = samples[i];
3581 if ((address < min) || (max <= address))
3584 long long a = address - min;
3585 long long b = numBuckets;
3586 long long c = addressSpace;
3587 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
3591 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3592 writeLong(f, min); /* low_pc */
3593 writeLong(f, max); /* high_pc */
3594 writeLong(f, numBuckets); /* # of buckets */
3595 writeLong(f, 100); /* KLUDGE! We lie, ca. 100Hz best case. */
3596 writeString(f, "seconds");
3597 for (i = 0; i < (15-strlen("seconds")); i++)
3598 writeData(f, &zero, 1);
3599 writeString(f, "s");
3601 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3603 char *data = malloc(2 * numBuckets);
3605 for (i = 0; i < numBuckets; i++) {
3610 data[i * 2] = val&0xff;
3611 data[i * 2 + 1] = (val >> 8) & 0xff;
3614 writeData(f, data, numBuckets * 2);
3622 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3623 * which will be used as a random sampling of PC */
3624 COMMAND_HANDLER(handle_profile_command)
3626 struct target *target = get_current_target(CMD_CTX);
3628 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
3629 return ERROR_COMMAND_SYNTAX_ERROR;
3631 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
3633 uint32_t num_of_samples;
3634 int retval = ERROR_OK;
3636 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
3638 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
3639 if (samples == NULL) {
3640 LOG_ERROR("No memory to store samples.");
3645 * Some cores let us sample the PC without the
3646 * annoying halt/resume step; for example, ARMv7 PCSR.
3647 * Provide a way to use that more efficient mechanism.
3649 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
3650 &num_of_samples, offset);
3651 if (retval != ERROR_OK) {
3656 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
3658 retval = target_poll(target);
3659 if (retval != ERROR_OK) {
3663 if (target->state == TARGET_RUNNING) {
3664 retval = target_halt(target);
3665 if (retval != ERROR_OK) {
3671 retval = target_poll(target);
3672 if (retval != ERROR_OK) {
3677 uint32_t start_address = 0;
3678 uint32_t end_address = 0;
3679 bool with_range = false;
3680 if (CMD_ARGC == 4) {
3682 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
3683 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
3686 write_gmon(samples, num_of_samples, CMD_ARGV[1],
3687 with_range, start_address, end_address);
3688 command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3694 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
3697 Jim_Obj *nameObjPtr, *valObjPtr;
3700 namebuf = alloc_printf("%s(%d)", varname, idx);
3704 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3705 valObjPtr = Jim_NewIntObj(interp, val);
3706 if (!nameObjPtr || !valObjPtr) {
3711 Jim_IncrRefCount(nameObjPtr);
3712 Jim_IncrRefCount(valObjPtr);
3713 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3714 Jim_DecrRefCount(interp, nameObjPtr);
3715 Jim_DecrRefCount(interp, valObjPtr);
3717 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3721 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3723 struct command_context *context;
3724 struct target *target;
3726 context = current_command_context(interp);
3727 assert(context != NULL);
3729 target = get_current_target(context);
3730 if (target == NULL) {
3731 LOG_ERROR("mem2array: no current target");
3735 return target_mem2array(interp, target, argc - 1, argv + 1);
3738 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3746 const char *varname;
3750 /* argv[1] = name of array to receive the data
3751 * argv[2] = desired width
3752 * argv[3] = memory address
3753 * argv[4] = count of times to read
3756 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3759 varname = Jim_GetString(argv[0], &len);
3760 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3762 e = Jim_GetLong(interp, argv[1], &l);
3767 e = Jim_GetLong(interp, argv[2], &l);
3771 e = Jim_GetLong(interp, argv[3], &l);
3786 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3787 Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3791 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3792 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3795 if ((addr + (len * width)) < addr) {
3796 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3797 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3800 /* absurd transfer size? */
3802 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3803 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3808 ((width == 2) && ((addr & 1) == 0)) ||
3809 ((width == 4) && ((addr & 3) == 0))) {
3813 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3814 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3817 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3826 size_t buffersize = 4096;
3827 uint8_t *buffer = malloc(buffersize);
3834 /* Slurp... in buffer size chunks */
3836 count = len; /* in objects.. */
3837 if (count > (buffersize / width))
3838 count = (buffersize / width);
3840 retval = target_read_memory(target, addr, width, count, buffer);
3841 if (retval != ERROR_OK) {
3843 LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3847 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3848 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3852 v = 0; /* shut up gcc */
3853 for (i = 0; i < count ; i++, n++) {
3856 v = target_buffer_get_u32(target, &buffer[i*width]);
3859 v = target_buffer_get_u16(target, &buffer[i*width]);
3862 v = buffer[i] & 0x0ff;
3865 new_int_array_element(interp, varname, n, v);
3868 addr += count * width;
3874 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3879 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
3882 Jim_Obj *nameObjPtr, *valObjPtr;
3886 namebuf = alloc_printf("%s(%d)", varname, idx);
3890 nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3896 Jim_IncrRefCount(nameObjPtr);
3897 valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3898 Jim_DecrRefCount(interp, nameObjPtr);
3900 if (valObjPtr == NULL)
3903 result = Jim_GetLong(interp, valObjPtr, &l);
3904 /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3909 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3911 struct command_context *context;
3912 struct target *target;
3914 context = current_command_context(interp);
3915 assert(context != NULL);
3917 target = get_current_target(context);
3918 if (target == NULL) {
3919 LOG_ERROR("array2mem: no current target");
3923 return target_array2mem(interp, target, argc-1, argv + 1);
3926 static int target_array2mem(Jim_Interp *interp, struct target *target,
3927 int argc, Jim_Obj *const *argv)
3935 const char *varname;
3939 /* argv[1] = name of array to get the data
3940 * argv[2] = desired width
3941 * argv[3] = memory address
3942 * argv[4] = count to write
3945 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3948 varname = Jim_GetString(argv[0], &len);
3949 /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3951 e = Jim_GetLong(interp, argv[1], &l);
3956 e = Jim_GetLong(interp, argv[2], &l);
3960 e = Jim_GetLong(interp, argv[3], &l);
3975 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3976 Jim_AppendStrings(interp, Jim_GetResult(interp),
3977 "Invalid width param, must be 8/16/32", NULL);
3981 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3982 Jim_AppendStrings(interp, Jim_GetResult(interp),
3983 "array2mem: zero width read?", NULL);
3986 if ((addr + (len * width)) < addr) {
3987 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3988 Jim_AppendStrings(interp, Jim_GetResult(interp),
3989 "array2mem: addr + len - wraps to zero?", NULL);
3992 /* absurd transfer size? */
3994 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3995 Jim_AppendStrings(interp, Jim_GetResult(interp),
3996 "array2mem: absurd > 64K item request", NULL);
4001 ((width == 2) && ((addr & 1) == 0)) ||
4002 ((width == 4) && ((addr & 3) == 0))) {
4006 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4007 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
4010 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
4021 size_t buffersize = 4096;
4022 uint8_t *buffer = malloc(buffersize);
4027 /* Slurp... in buffer size chunks */
4029 count = len; /* in objects.. */
4030 if (count > (buffersize / width))
4031 count = (buffersize / width);
4033 v = 0; /* shut up gcc */
4034 for (i = 0; i < count; i++, n++) {
4035 get_int_array_element(interp, varname, n, &v);
4038 target_buffer_set_u32(target, &buffer[i * width], v);
4041 target_buffer_set_u16(target, &buffer[i * width], v);
4044 buffer[i] = v & 0x0ff;
4050 retval = target_write_memory(target, addr, width, count, buffer);
4051 if (retval != ERROR_OK) {
4053 LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
4057 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4058 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4062 addr += count * width;
4067 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4072 /* FIX? should we propagate errors here rather than printing them
4075 void target_handle_event(struct target *target, enum target_event e)
4077 struct target_event_action *teap;
4079 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4080 if (teap->event == e) {
4081 LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
4082 target->target_number,
4083 target_name(target),
4084 target_type_name(target),
4086 Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4087 Jim_GetString(teap->body, NULL));
4088 if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK) {
4089 Jim_MakeErrorMessage(teap->interp);
4090 command_print(NULL, "%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
4097 * Returns true only if the target has a handler for the specified event.
4099 bool target_has_event_action(struct target *target, enum target_event event)
4101 struct target_event_action *teap;
4103 for (teap = target->event_action; teap != NULL; teap = teap->next) {
4104 if (teap->event == event)
4110 enum target_cfg_param {
4113 TCFG_WORK_AREA_VIRT,
4114 TCFG_WORK_AREA_PHYS,
4115 TCFG_WORK_AREA_SIZE,
4116 TCFG_WORK_AREA_BACKUP,
4119 TCFG_CHAIN_POSITION,
4124 static Jim_Nvp nvp_config_opts[] = {
4125 { .name = "-type", .value = TCFG_TYPE },
4126 { .name = "-event", .value = TCFG_EVENT },
4127 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
4128 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
4129 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
4130 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4131 { .name = "-endian" , .value = TCFG_ENDIAN },
4132 { .name = "-coreid", .value = TCFG_COREID },
4133 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
4134 { .name = "-dbgbase", .value = TCFG_DBGBASE },
4135 { .name = "-rtos", .value = TCFG_RTOS },
4136 { .name = NULL, .value = -1 }
4139 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4146 /* parse config or cget options ... */
4147 while (goi->argc > 0) {
4148 Jim_SetEmptyResult(goi->interp);
4149 /* Jim_GetOpt_Debug(goi); */
4151 if (target->type->target_jim_configure) {
4152 /* target defines a configure function */
4153 /* target gets first dibs on parameters */
4154 e = (*(target->type->target_jim_configure))(target, goi);
4163 /* otherwise we 'continue' below */
4165 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4167 Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4173 if (goi->isconfigure) {
4174 Jim_SetResultFormatted(goi->interp,
4175 "not settable: %s", n->name);
4179 if (goi->argc != 0) {
4180 Jim_WrongNumArgs(goi->interp,
4181 goi->argc, goi->argv,
4186 Jim_SetResultString(goi->interp,
4187 target_type_name(target), -1);
4191 if (goi->argc == 0) {
4192 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4196 e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4198 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4202 if (goi->isconfigure) {
4203 if (goi->argc != 1) {
4204 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4208 if (goi->argc != 0) {
4209 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4215 struct target_event_action *teap;
4217 teap = target->event_action;
4218 /* replace existing? */
4220 if (teap->event == (enum target_event)n->value)
4225 if (goi->isconfigure) {
4226 bool replace = true;
4229 teap = calloc(1, sizeof(*teap));
4232 teap->event = n->value;
4233 teap->interp = goi->interp;
4234 Jim_GetOpt_Obj(goi, &o);
4236 Jim_DecrRefCount(teap->interp, teap->body);
4237 teap->body = Jim_DuplicateObj(goi->interp, o);
4240 * Tcl/TK - "tk events" have a nice feature.
4241 * See the "BIND" command.
4242 * We should support that here.
4243 * You can specify %X and %Y in the event code.
4244 * The idea is: %T - target name.
4245 * The idea is: %N - target number
4246 * The idea is: %E - event name.
4248 Jim_IncrRefCount(teap->body);
4251 /* add to head of event list */
4252 teap->next = target->event_action;
4253 target->event_action = teap;
4255 Jim_SetEmptyResult(goi->interp);
4259 Jim_SetEmptyResult(goi->interp);
4261 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4267 case TCFG_WORK_AREA_VIRT:
4268 if (goi->isconfigure) {
4269 target_free_all_working_areas(target);
4270 e = Jim_GetOpt_Wide(goi, &w);
4273 target->working_area_virt = w;
4274 target->working_area_virt_spec = true;
4279 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4283 case TCFG_WORK_AREA_PHYS:
4284 if (goi->isconfigure) {
4285 target_free_all_working_areas(target);
4286 e = Jim_GetOpt_Wide(goi, &w);
4289 target->working_area_phys = w;
4290 target->working_area_phys_spec = true;
4295 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4299 case TCFG_WORK_AREA_SIZE:
4300 if (goi->isconfigure) {
4301 target_free_all_working_areas(target);
4302 e = Jim_GetOpt_Wide(goi, &w);
4305 target->working_area_size = w;
4310 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4314 case TCFG_WORK_AREA_BACKUP:
4315 if (goi->isconfigure) {
4316 target_free_all_working_areas(target);
4317 e = Jim_GetOpt_Wide(goi, &w);
4320 /* make this exactly 1 or 0 */
4321 target->backup_working_area = (!!w);
4326 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4327 /* loop for more e*/
4332 if (goi->isconfigure) {
4333 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4335 Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4338 target->endianness = n->value;
4343 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4344 if (n->name == NULL) {
4345 target->endianness = TARGET_LITTLE_ENDIAN;
4346 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4348 Jim_SetResultString(goi->interp, n->name, -1);
4353 if (goi->isconfigure) {
4354 e = Jim_GetOpt_Wide(goi, &w);
4357 target->coreid = (int32_t)w;
4362 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4366 case TCFG_CHAIN_POSITION:
4367 if (goi->isconfigure) {
4369 struct jtag_tap *tap;
4370 target_free_all_working_areas(target);
4371 e = Jim_GetOpt_Obj(goi, &o_t);
4374 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4377 /* make this exactly 1 or 0 */
4383 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4384 /* loop for more e*/
4387 if (goi->isconfigure) {
4388 e = Jim_GetOpt_Wide(goi, &w);
4391 target->dbgbase = (uint32_t)w;
4392 target->dbgbase_set = true;
4397 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4404 int result = rtos_create(goi, target);
4405 if (result != JIM_OK)
4411 } /* while (goi->argc) */
4414 /* done - we return */
4418 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4422 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4423 goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4424 int need_args = 1 + goi.isconfigure;
4425 if (goi.argc < need_args) {
4426 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4428 ? "missing: -option VALUE ..."
4429 : "missing: -option ...");
4432 struct target *target = Jim_CmdPrivData(goi.interp);
4433 return target_configure(&goi, target);
4436 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4438 const char *cmd_name = Jim_GetString(argv[0], NULL);
4441 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4443 if (goi.argc < 2 || goi.argc > 4) {
4444 Jim_SetResultFormatted(goi.interp,
4445 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4450 fn = target_write_memory;
4453 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4455 struct Jim_Obj *obj;
4456 e = Jim_GetOpt_Obj(&goi, &obj);
4460 fn = target_write_phys_memory;
4464 e = Jim_GetOpt_Wide(&goi, &a);
4469 e = Jim_GetOpt_Wide(&goi, &b);
4474 if (goi.argc == 1) {
4475 e = Jim_GetOpt_Wide(&goi, &c);
4480 /* all args must be consumed */
4484 struct target *target = Jim_CmdPrivData(goi.interp);
4486 if (strcasecmp(cmd_name, "mww") == 0)
4488 else if (strcasecmp(cmd_name, "mwh") == 0)
4490 else if (strcasecmp(cmd_name, "mwb") == 0)
4493 LOG_ERROR("command '%s' unknown: ", cmd_name);
4497 return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4501 * @brief Reads an array of words/halfwords/bytes from target memory starting at specified address.
4503 * Usage: mdw [phys] <address> [<count>] - for 32 bit reads
4504 * mdh [phys] <address> [<count>] - for 16 bit reads
4505 * mdb [phys] <address> [<count>] - for 8 bit reads
4507 * Count defaults to 1.
4509 * Calls target_read_memory or target_read_phys_memory depending on
4510 * the presence of the "phys" argument
4511 * Reads the target memory in blocks of max. 32 bytes, and returns an array of ints formatted
4512 * to int representation in base16.
4513 * Also outputs read data in a human readable form using command_print
4515 * @param phys if present target_read_phys_memory will be used instead of target_read_memory
4516 * @param address address where to start the read. May be specified in decimal or hex using the standard "0x" prefix
4517 * @param count optional count parameter to read an array of values. If not specified, defaults to 1.
4518 * @returns: JIM_ERR on error or JIM_OK on success and sets the result string to an array of ascii formatted numbers
4519 * on success, with [<count>] number of elements.
4521 * In case of little endian target:
4522 * Example1: "mdw 0x00000000" returns "10123456"
4523 * Exmaple2: "mdh 0x00000000 1" returns "3456"
4524 * Example3: "mdb 0x00000000" returns "56"
4525 * Example4: "mdh 0x00000000 2" returns "3456 1012"
4526 * Example5: "mdb 0x00000000 3" returns "56 34 12"
4528 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4530 const char *cmd_name = Jim_GetString(argv[0], NULL);
4533 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4535 if ((goi.argc < 1) || (goi.argc > 3)) {
4536 Jim_SetResultFormatted(goi.interp,
4537 "usage: %s [phys] <address> [<count>]", cmd_name);
4541 int (*fn)(struct target *target,
4542 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4543 fn = target_read_memory;
4546 if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0) {
4548 struct Jim_Obj *obj;
4549 e = Jim_GetOpt_Obj(&goi, &obj);
4553 fn = target_read_phys_memory;
4556 /* Read address parameter */
4558 e = Jim_GetOpt_Wide(&goi, &addr);
4562 /* If next parameter exists, read it out as the count parameter, if not, set it to 1 (default) */
4564 if (goi.argc == 1) {
4565 e = Jim_GetOpt_Wide(&goi, &count);
4571 /* all args must be consumed */
4575 jim_wide dwidth = 1; /* shut up gcc */
4576 if (strcasecmp(cmd_name, "mdw") == 0)
4578 else if (strcasecmp(cmd_name, "mdh") == 0)
4580 else if (strcasecmp(cmd_name, "mdb") == 0)
4583 LOG_ERROR("command '%s' unknown: ", cmd_name);
4587 /* convert count to "bytes" */
4588 int bytes = count * dwidth;
4590 struct target *target = Jim_CmdPrivData(goi.interp);
4591 uint8_t target_buf[32];
4594 y = (bytes < 16) ? bytes : 16; /* y = min(bytes, 16); */
4596 /* Try to read out next block */
4597 e = fn(target, addr, dwidth, y / dwidth, target_buf);
4599 if (e != ERROR_OK) {
4600 Jim_SetResultFormatted(interp, "error reading target @ 0x%08lx", (long)addr);
4604 command_print_sameline(NULL, "0x%08x ", (int)(addr));
4607 for (x = 0; x < 16 && x < y; x += 4) {
4608 z = target_buffer_get_u32(target, &(target_buf[x]));
4609 command_print_sameline(NULL, "%08x ", (int)(z));
4611 for (; (x < 16) ; x += 4)
4612 command_print_sameline(NULL, " ");
4615 for (x = 0; x < 16 && x < y; x += 2) {
4616 z = target_buffer_get_u16(target, &(target_buf[x]));
4617 command_print_sameline(NULL, "%04x ", (int)(z));
4619 for (; (x < 16) ; x += 2)
4620 command_print_sameline(NULL, " ");
4624 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4625 z = target_buffer_get_u8(target, &(target_buf[x]));
4626 command_print_sameline(NULL, "%02x ", (int)(z));
4628 for (; (x < 16) ; x += 1)
4629 command_print_sameline(NULL, " ");
4632 /* ascii-ify the bytes */
4633 for (x = 0 ; x < y ; x++) {
4634 if ((target_buf[x] >= 0x20) &&
4635 (target_buf[x] <= 0x7e)) {
4639 target_buf[x] = '.';
4644 target_buf[x] = ' ';
4649 /* print - with a newline */
4650 command_print_sameline(NULL, "%s\n", target_buf);
4658 static int jim_target_mem2array(Jim_Interp *interp,
4659 int argc, Jim_Obj *const *argv)
4661 struct target *target = Jim_CmdPrivData(interp);
4662 return target_mem2array(interp, target, argc - 1, argv + 1);
4665 static int jim_target_array2mem(Jim_Interp *interp,
4666 int argc, Jim_Obj *const *argv)
4668 struct target *target = Jim_CmdPrivData(interp);
4669 return target_array2mem(interp, target, argc - 1, argv + 1);
4672 static int jim_target_tap_disabled(Jim_Interp *interp)
4674 Jim_SetResultFormatted(interp, "[TAP is disabled]");
4678 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4681 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4684 struct target *target = Jim_CmdPrivData(interp);
4685 if (!target->tap->enabled)
4686 return jim_target_tap_disabled(interp);
4688 int e = target->type->examine(target);
4694 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4697 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4700 struct target *target = Jim_CmdPrivData(interp);
4702 if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4708 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4711 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4714 struct target *target = Jim_CmdPrivData(interp);
4715 if (!target->tap->enabled)
4716 return jim_target_tap_disabled(interp);
4719 if (!(target_was_examined(target)))
4720 e = ERROR_TARGET_NOT_EXAMINED;
4722 e = target->type->poll(target);
4728 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4731 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4733 if (goi.argc != 2) {
4734 Jim_WrongNumArgs(interp, 0, argv,
4735 "([tT]|[fF]|assert|deassert) BOOL");
4740 int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4742 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4745 /* the halt or not param */
4747 e = Jim_GetOpt_Wide(&goi, &a);
4751 struct target *target = Jim_CmdPrivData(goi.interp);
4752 if (!target->tap->enabled)
4753 return jim_target_tap_disabled(interp);
4754 if (!(target_was_examined(target))) {
4755 LOG_ERROR("Target not examined yet");
4756 return ERROR_TARGET_NOT_EXAMINED;
4758 if (!target->type->assert_reset || !target->type->deassert_reset) {
4759 Jim_SetResultFormatted(interp,
4760 "No target-specific reset for %s",
4761 target_name(target));
4764 /* determine if we should halt or not. */
4765 target->reset_halt = !!a;
4766 /* When this happens - all workareas are invalid. */
4767 target_free_all_working_areas_restore(target, 0);
4770 if (n->value == NVP_ASSERT)
4771 e = target->type->assert_reset(target);
4773 e = target->type->deassert_reset(target);
4774 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4777 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4780 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4783 struct target *target = Jim_CmdPrivData(interp);
4784 if (!target->tap->enabled)
4785 return jim_target_tap_disabled(interp);
4786 int e = target->type->halt(target);
4787 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4790 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4793 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4795 /* params: <name> statename timeoutmsecs */
4796 if (goi.argc != 2) {
4797 const char *cmd_name = Jim_GetString(argv[0], NULL);
4798 Jim_SetResultFormatted(goi.interp,
4799 "%s <state_name> <timeout_in_msec>", cmd_name);
4804 int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4806 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
4810 e = Jim_GetOpt_Wide(&goi, &a);
4813 struct target *target = Jim_CmdPrivData(interp);
4814 if (!target->tap->enabled)
4815 return jim_target_tap_disabled(interp);
4817 e = target_wait_state(target, n->value, a);
4818 if (e != ERROR_OK) {
4819 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4820 Jim_SetResultFormatted(goi.interp,
4821 "target: %s wait %s fails (%#s) %s",
4822 target_name(target), n->name,
4823 eObj, target_strerror_safe(e));
4824 Jim_FreeNewObj(interp, eObj);
4829 /* List for human, Events defined for this target.
4830 * scripts/programs should use 'name cget -event NAME'
4832 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4834 struct command_context *cmd_ctx = current_command_context(interp);
4835 assert(cmd_ctx != NULL);
4837 struct target *target = Jim_CmdPrivData(interp);
4838 struct target_event_action *teap = target->event_action;
4839 command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4840 target->target_number,
4841 target_name(target));
4842 command_print(cmd_ctx, "%-25s | Body", "Event");
4843 command_print(cmd_ctx, "------------------------- | "
4844 "----------------------------------------");
4846 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4847 command_print(cmd_ctx, "%-25s | %s",
4848 opt->name, Jim_GetString(teap->body, NULL));
4851 command_print(cmd_ctx, "***END***");
4854 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4857 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4860 struct target *target = Jim_CmdPrivData(interp);
4861 Jim_SetResultString(interp, target_state_name(target), -1);
4864 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4867 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4868 if (goi.argc != 1) {
4869 const char *cmd_name = Jim_GetString(argv[0], NULL);
4870 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4874 int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4876 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4879 struct target *target = Jim_CmdPrivData(interp);
4880 target_handle_event(target, n->value);
4884 static const struct command_registration target_instance_command_handlers[] = {
4886 .name = "configure",
4887 .mode = COMMAND_CONFIG,
4888 .jim_handler = jim_target_configure,
4889 .help = "configure a new target for use",
4890 .usage = "[target_attribute ...]",
4894 .mode = COMMAND_ANY,
4895 .jim_handler = jim_target_configure,
4896 .help = "returns the specified target attribute",
4897 .usage = "target_attribute",
4901 .mode = COMMAND_EXEC,
4902 .jim_handler = jim_target_mw,
4903 .help = "Write 32-bit word(s) to target memory",
4904 .usage = "address data [count]",
4908 .mode = COMMAND_EXEC,
4909 .jim_handler = jim_target_mw,
4910 .help = "Write 16-bit half-word(s) to target memory",
4911 .usage = "address data [count]",
4915 .mode = COMMAND_EXEC,
4916 .jim_handler = jim_target_mw,
4917 .help = "Write byte(s) to target memory",
4918 .usage = "address data [count]",
4922 .mode = COMMAND_EXEC,
4923 .jim_handler = jim_target_md,
4924 .help = "Display target memory as 32-bit words",
4925 .usage = "address [count]",
4929 .mode = COMMAND_EXEC,
4930 .jim_handler = jim_target_md,
4931 .help = "Display target memory as 16-bit half-words",
4932 .usage = "address [count]",
4936 .mode = COMMAND_EXEC,
4937 .jim_handler = jim_target_md,
4938 .help = "Display target memory as 8-bit bytes",
4939 .usage = "address [count]",
4942 .name = "array2mem",
4943 .mode = COMMAND_EXEC,
4944 .jim_handler = jim_target_array2mem,
4945 .help = "Writes Tcl array of 8/16/32 bit numbers "
4947 .usage = "arrayname bitwidth address count",
4950 .name = "mem2array",
4951 .mode = COMMAND_EXEC,
4952 .jim_handler = jim_target_mem2array,
4953 .help = "Loads Tcl array of 8/16/32 bit numbers "
4954 "from target memory",
4955 .usage = "arrayname bitwidth address count",
4958 .name = "eventlist",
4959 .mode = COMMAND_EXEC,
4960 .jim_handler = jim_target_event_list,
4961 .help = "displays a table of events defined for this target",
4965 .mode = COMMAND_EXEC,
4966 .jim_handler = jim_target_current_state,
4967 .help = "displays the current state of this target",
4970 .name = "arp_examine",
4971 .mode = COMMAND_EXEC,
4972 .jim_handler = jim_target_examine,
4973 .help = "used internally for reset processing",
4976 .name = "arp_halt_gdb",
4977 .mode = COMMAND_EXEC,
4978 .jim_handler = jim_target_halt_gdb,
4979 .help = "used internally for reset processing to halt GDB",
4983 .mode = COMMAND_EXEC,
4984 .jim_handler = jim_target_poll,
4985 .help = "used internally for reset processing",
4988 .name = "arp_reset",
4989 .mode = COMMAND_EXEC,
4990 .jim_handler = jim_target_reset,
4991 .help = "used internally for reset processing",
4995 .mode = COMMAND_EXEC,
4996 .jim_handler = jim_target_halt,
4997 .help = "used internally for reset processing",
5000 .name = "arp_waitstate",
5001 .mode = COMMAND_EXEC,
5002 .jim_handler = jim_target_wait_state,
5003 .help = "used internally for reset processing",
5006 .name = "invoke-event",
5007 .mode = COMMAND_EXEC,
5008 .jim_handler = jim_target_invoke_event,
5009 .help = "invoke handler for specified event",
5010 .usage = "event_name",
5012 COMMAND_REGISTRATION_DONE
5015 static int target_create(Jim_GetOptInfo *goi)
5023 struct target *target;
5024 struct command_context *cmd_ctx;
5026 cmd_ctx = current_command_context(goi->interp);
5027 assert(cmd_ctx != NULL);
5029 if (goi->argc < 3) {
5030 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5035 Jim_GetOpt_Obj(goi, &new_cmd);
5036 /* does this command exist? */
5037 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5039 cp = Jim_GetString(new_cmd, NULL);
5040 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5045 e = Jim_GetOpt_String(goi, &cp2, NULL);
5049 struct transport *tr = get_current_transport();
5050 if (tr->override_target) {
5051 e = tr->override_target(&cp);
5052 if (e != ERROR_OK) {
5053 LOG_ERROR("The selected transport doesn't support this target");
5056 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5058 /* now does target type exist */
5059 for (x = 0 ; target_types[x] ; x++) {
5060 if (0 == strcmp(cp, target_types[x]->name)) {
5065 /* check for deprecated name */
5066 if (target_types[x]->deprecated_name) {
5067 if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5069 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5074 if (target_types[x] == NULL) {
5075 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5076 for (x = 0 ; target_types[x] ; x++) {
5077 if (target_types[x + 1]) {
5078 Jim_AppendStrings(goi->interp,
5079 Jim_GetResult(goi->interp),
5080 target_types[x]->name,
5083 Jim_AppendStrings(goi->interp,
5084 Jim_GetResult(goi->interp),
5086 target_types[x]->name, NULL);
5093 target = calloc(1, sizeof(struct target));
5094 /* set target number */
5095 target->target_number = new_target_number();
5096 cmd_ctx->current_target = target->target_number;
5098 /* allocate memory for each unique target type */
5099 target->type = calloc(1, sizeof(struct target_type));
5101 memcpy(target->type, target_types[x], sizeof(struct target_type));
5103 /* will be set by "-endian" */
5104 target->endianness = TARGET_ENDIAN_UNKNOWN;
5106 /* default to first core, override with -coreid */
5109 target->working_area = 0x0;
5110 target->working_area_size = 0x0;
5111 target->working_areas = NULL;
5112 target->backup_working_area = 0;
5114 target->state = TARGET_UNKNOWN;
5115 target->debug_reason = DBG_REASON_UNDEFINED;
5116 target->reg_cache = NULL;
5117 target->breakpoints = NULL;
5118 target->watchpoints = NULL;
5119 target->next = NULL;
5120 target->arch_info = NULL;
5122 target->display = 1;
5124 target->halt_issued = false;
5126 /* initialize trace information */
5127 target->trace_info = malloc(sizeof(struct trace));
5128 target->trace_info->num_trace_points = 0;
5129 target->trace_info->trace_points_size = 0;
5130 target->trace_info->trace_points = NULL;
5131 target->trace_info->trace_history_size = 0;
5132 target->trace_info->trace_history = NULL;
5133 target->trace_info->trace_history_pos = 0;
5134 target->trace_info->trace_history_overflowed = 0;
5136 target->dbgmsg = NULL;
5137 target->dbg_msg_enabled = 0;
5139 target->endianness = TARGET_ENDIAN_UNKNOWN;
5141 target->rtos = NULL;
5142 target->rtos_auto_detect = false;
5144 /* Do the rest as "configure" options */
5145 goi->isconfigure = 1;
5146 e = target_configure(goi, target);
5148 if (target->tap == NULL) {
5149 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
5159 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5160 /* default endian to little if not specified */
5161 target->endianness = TARGET_LITTLE_ENDIAN;
5164 cp = Jim_GetString(new_cmd, NULL);
5165 target->cmd_name = strdup(cp);
5167 /* create the target specific commands */
5168 if (target->type->commands) {
5169 e = register_commands(cmd_ctx, NULL, target->type->commands);
5171 LOG_ERROR("unable to register '%s' commands", cp);
5173 if (target->type->target_create)
5174 (*(target->type->target_create))(target, goi->interp);
5176 /* append to end of list */
5178 struct target **tpp;
5179 tpp = &(all_targets);
5181 tpp = &((*tpp)->next);
5185 /* now - create the new target name command */
5186 const struct command_registration target_subcommands[] = {
5188 .chain = target_instance_command_handlers,
5191 .chain = target->type->commands,
5193 COMMAND_REGISTRATION_DONE
5195 const struct command_registration target_commands[] = {
5198 .mode = COMMAND_ANY,
5199 .help = "target command group",
5201 .chain = target_subcommands,
5203 COMMAND_REGISTRATION_DONE
5205 e = register_commands(cmd_ctx, NULL, target_commands);
5209 struct command *c = command_find_in_context(cmd_ctx, cp);
5211 command_set_handler_data(c, target);
5213 return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5216 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5219 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5222 struct command_context *cmd_ctx = current_command_context(interp);
5223 assert(cmd_ctx != NULL);
5225 Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5229 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5232 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5235 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5236 for (unsigned x = 0; NULL != target_types[x]; x++) {
5237 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5238 Jim_NewStringObj(interp, target_types[x]->name, -1));
5243 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5246 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5249 Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5250 struct target *target = all_targets;
5252 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5253 Jim_NewStringObj(interp, target_name(target), -1));
5254 target = target->next;
5259 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5262 const char *targetname;
5264 struct target *target = (struct target *) NULL;
5265 struct target_list *head, *curr, *new;
5266 curr = (struct target_list *) NULL;
5267 head = (struct target_list *) NULL;
5270 LOG_DEBUG("%d", argc);
5271 /* argv[1] = target to associate in smp
5272 * argv[2] = target to assoicate in smp
5276 for (i = 1; i < argc; i++) {
5278 targetname = Jim_GetString(argv[i], &len);
5279 target = get_target(targetname);
5280 LOG_DEBUG("%s ", targetname);
5282 new = malloc(sizeof(struct target_list));
5283 new->target = target;
5284 new->next = (struct target_list *)NULL;
5285 if (head == (struct target_list *)NULL) {
5294 /* now parse the list of cpu and put the target in smp mode*/
5297 while (curr != (struct target_list *)NULL) {
5298 target = curr->target;
5300 target->head = head;
5304 if (target && target->rtos)
5305 retval = rtos_smp_init(head->target);
5311 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5314 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5316 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5317 "<name> <target_type> [<target_options> ...]");
5320 return target_create(&goi);
5323 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5326 Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5328 /* It's OK to remove this mechanism sometime after August 2010 or so */
5329 LOG_WARNING("don't use numbers as target identifiers; use names");
5330 if (goi.argc != 1) {
5331 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
5335 int e = Jim_GetOpt_Wide(&goi, &w);
5339 struct target *target;
5340 for (target = all_targets; NULL != target; target = target->next) {
5341 if (target->target_number != w)
5344 Jim_SetResultString(goi.interp, target_name(target), -1);
5348 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
5349 Jim_SetResultFormatted(goi.interp,
5350 "Target: number %#s does not exist", wObj);
5351 Jim_FreeNewObj(interp, wObj);
5356 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5359 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5363 struct target *target = all_targets;
5364 while (NULL != target) {
5365 target = target->next;
5368 Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5372 static const struct command_registration target_subcommand_handlers[] = {
5375 .mode = COMMAND_CONFIG,
5376 .handler = handle_target_init_command,
5377 .help = "initialize targets",
5381 /* REVISIT this should be COMMAND_CONFIG ... */
5382 .mode = COMMAND_ANY,
5383 .jim_handler = jim_target_create,
5384 .usage = "name type '-chain-position' name [options ...]",
5385 .help = "Creates and selects a new target",
5389 .mode = COMMAND_ANY,
5390 .jim_handler = jim_target_current,
5391 .help = "Returns the currently selected target",
5395 .mode = COMMAND_ANY,
5396 .jim_handler = jim_target_types,
5397 .help = "Returns the available target types as "
5398 "a list of strings",
5402 .mode = COMMAND_ANY,
5403 .jim_handler = jim_target_names,
5404 .help = "Returns the names of all targets as a list of strings",
5408 .mode = COMMAND_ANY,
5409 .jim_handler = jim_target_number,
5411 .help = "Returns the name of the numbered target "
5416 .mode = COMMAND_ANY,
5417 .jim_handler = jim_target_count,
5418 .help = "Returns the number of targets as an integer "
5423 .mode = COMMAND_ANY,
5424 .jim_handler = jim_target_smp,
5425 .usage = "targetname1 targetname2 ...",
5426 .help = "gather several target in a smp list"
5429 COMMAND_REGISTRATION_DONE
5439 static int fastload_num;
5440 static struct FastLoad *fastload;
5442 static void free_fastload(void)
5444 if (fastload != NULL) {
5446 for (i = 0; i < fastload_num; i++) {
5447 if (fastload[i].data)
5448 free(fastload[i].data);
5455 COMMAND_HANDLER(handle_fast_load_image_command)
5459 uint32_t image_size;
5460 uint32_t min_address = 0;
5461 uint32_t max_address = 0xffffffff;
5466 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5467 &image, &min_address, &max_address);
5468 if (ERROR_OK != retval)
5471 struct duration bench;
5472 duration_start(&bench);
5474 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5475 if (retval != ERROR_OK)
5480 fastload_num = image.num_sections;
5481 fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5482 if (fastload == NULL) {
5483 command_print(CMD_CTX, "out of memory");
5484 image_close(&image);
5487 memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5488 for (i = 0; i < image.num_sections; i++) {
5489 buffer = malloc(image.sections[i].size);
5490 if (buffer == NULL) {
5491 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5492 (int)(image.sections[i].size));
5493 retval = ERROR_FAIL;
5497 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5498 if (retval != ERROR_OK) {
5503 uint32_t offset = 0;
5504 uint32_t length = buf_cnt;
5506 /* DANGER!!! beware of unsigned comparision here!!! */
5508 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5509 (image.sections[i].base_address < max_address)) {
5510 if (image.sections[i].base_address < min_address) {
5511 /* clip addresses below */
5512 offset += min_address-image.sections[i].base_address;
5516 if (image.sections[i].base_address + buf_cnt > max_address)
5517 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5519 fastload[i].address = image.sections[i].base_address + offset;
5520 fastload[i].data = malloc(length);
5521 if (fastload[i].data == NULL) {
5523 command_print(CMD_CTX, "error allocating buffer for section (%" PRIu32 " bytes)",
5525 retval = ERROR_FAIL;
5528 memcpy(fastload[i].data, buffer + offset, length);
5529 fastload[i].length = length;
5531 image_size += length;
5532 command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5533 (unsigned int)length,
5534 ((unsigned int)(image.sections[i].base_address + offset)));
5540 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5541 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5542 "in %fs (%0.3f KiB/s)", image_size,
5543 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5545 command_print(CMD_CTX,
5546 "WARNING: image has not been loaded to target!"
5547 "You can issue a 'fast_load' to finish loading.");
5550 image_close(&image);
5552 if (retval != ERROR_OK)
5558 COMMAND_HANDLER(handle_fast_load_command)
5561 return ERROR_COMMAND_SYNTAX_ERROR;
5562 if (fastload == NULL) {
5563 LOG_ERROR("No image in memory");
5567 int ms = timeval_ms();
5569 int retval = ERROR_OK;
5570 for (i = 0; i < fastload_num; i++) {
5571 struct target *target = get_current_target(CMD_CTX);
5572 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5573 (unsigned int)(fastload[i].address),
5574 (unsigned int)(fastload[i].length));
5575 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5576 if (retval != ERROR_OK)
5578 size += fastload[i].length;
5580 if (retval == ERROR_OK) {
5581 int after = timeval_ms();
5582 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5587 static const struct command_registration target_command_handlers[] = {
5590 .handler = handle_targets_command,
5591 .mode = COMMAND_ANY,
5592 .help = "change current default target (one parameter) "
5593 "or prints table of all targets (no parameters)",
5594 .usage = "[target]",
5598 .mode = COMMAND_CONFIG,
5599 .help = "configure target",
5601 .chain = target_subcommand_handlers,
5603 COMMAND_REGISTRATION_DONE
5606 int target_register_commands(struct command_context *cmd_ctx)
5608 return register_commands(cmd_ctx, NULL, target_command_handlers);
5611 static bool target_reset_nag = true;
5613 bool get_target_reset_nag(void)
5615 return target_reset_nag;
5618 COMMAND_HANDLER(handle_target_reset_nag)
5620 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5621 &target_reset_nag, "Nag after each reset about options to improve "
5625 COMMAND_HANDLER(handle_ps_command)
5627 struct target *target = get_current_target(CMD_CTX);
5629 if (target->state != TARGET_HALTED) {
5630 LOG_INFO("target not halted !!");
5634 if ((target->rtos) && (target->rtos->type)
5635 && (target->rtos->type->ps_command)) {
5636 display = target->rtos->type->ps_command(target);
5637 command_print(CMD_CTX, "%s", display);
5642 return ERROR_TARGET_FAILURE;
5646 static void binprint(struct command_context *cmd_ctx, const char *text, const uint8_t *buf, int size)
5649 command_print_sameline(cmd_ctx, "%s", text);
5650 for (int i = 0; i < size; i++)
5651 command_print_sameline(cmd_ctx, " %02x", buf[i]);
5652 command_print(cmd_ctx, " ");
5655 COMMAND_HANDLER(handle_test_mem_access_command)
5657 struct target *target = get_current_target(CMD_CTX);
5659 int retval = ERROR_OK;
5661 if (target->state != TARGET_HALTED) {
5662 LOG_INFO("target not halted !!");
5667 return ERROR_COMMAND_SYNTAX_ERROR;
5669 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5672 size_t num_bytes = test_size + 4;
5674 struct working_area *wa = NULL;
5675 retval = target_alloc_working_area(target, num_bytes, &wa);
5676 if (retval != ERROR_OK) {
5677 LOG_ERROR("Not enough working area");
5681 uint8_t *test_pattern = malloc(num_bytes);
5683 for (size_t i = 0; i < num_bytes; i++)
5684 test_pattern[i] = rand();
5686 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5687 if (retval != ERROR_OK) {
5688 LOG_ERROR("Test pattern write failed");
5692 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5693 for (int size = 1; size <= 4; size *= 2) {
5694 for (int offset = 0; offset < 4; offset++) {
5695 uint32_t count = test_size / size;
5696 size_t host_bufsiz = (count + 2) * size + host_offset;
5697 uint8_t *read_ref = malloc(host_bufsiz);
5698 uint8_t *read_buf = malloc(host_bufsiz);
5700 for (size_t i = 0; i < host_bufsiz; i++) {
5701 read_ref[i] = rand();
5702 read_buf[i] = read_ref[i];
5704 command_print_sameline(CMD_CTX,
5705 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
5706 size, offset, host_offset ? "un" : "");
5708 struct duration bench;
5709 duration_start(&bench);
5711 retval = target_read_memory(target, wa->address + offset, size, count,
5712 read_buf + size + host_offset);
5714 duration_measure(&bench);
5716 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5717 command_print(CMD_CTX, "Unsupported alignment");
5719 } else if (retval != ERROR_OK) {
5720 command_print(CMD_CTX, "Memory read failed");
5724 /* replay on host */
5725 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
5728 int result = memcmp(read_ref, read_buf, host_bufsiz);
5730 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5731 duration_elapsed(&bench),
5732 duration_kbps(&bench, count * size));
5734 command_print(CMD_CTX, "Compare failed");
5735 binprint(CMD_CTX, "ref:", read_ref, host_bufsiz);
5736 binprint(CMD_CTX, "buf:", read_buf, host_bufsiz);
5749 target_free_working_area(target, wa);
5752 num_bytes = test_size + 4 + 4 + 4;
5754 retval = target_alloc_working_area(target, num_bytes, &wa);
5755 if (retval != ERROR_OK) {
5756 LOG_ERROR("Not enough working area");
5760 test_pattern = malloc(num_bytes);
5762 for (size_t i = 0; i < num_bytes; i++)
5763 test_pattern[i] = rand();
5765 for (int host_offset = 0; host_offset <= 1; host_offset++) {
5766 for (int size = 1; size <= 4; size *= 2) {
5767 for (int offset = 0; offset < 4; offset++) {
5768 uint32_t count = test_size / size;
5769 size_t host_bufsiz = count * size + host_offset;
5770 uint8_t *read_ref = malloc(num_bytes);
5771 uint8_t *read_buf = malloc(num_bytes);
5772 uint8_t *write_buf = malloc(host_bufsiz);
5774 for (size_t i = 0; i < host_bufsiz; i++)
5775 write_buf[i] = rand();
5776 command_print_sameline(CMD_CTX,
5777 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
5778 size, offset, host_offset ? "un" : "");
5780 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
5781 if (retval != ERROR_OK) {
5782 command_print(CMD_CTX, "Test pattern write failed");
5786 /* replay on host */
5787 memcpy(read_ref, test_pattern, num_bytes);
5788 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
5790 struct duration bench;
5791 duration_start(&bench);
5793 retval = target_write_memory(target, wa->address + size + offset, size, count,
5794 write_buf + host_offset);
5796 duration_measure(&bench);
5798 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
5799 command_print(CMD_CTX, "Unsupported alignment");
5801 } else if (retval != ERROR_OK) {
5802 command_print(CMD_CTX, "Memory write failed");
5807 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
5808 if (retval != ERROR_OK) {
5809 command_print(CMD_CTX, "Test pattern write failed");
5814 int result = memcmp(read_ref, read_buf, num_bytes);
5816 command_print(CMD_CTX, "Pass in %fs (%0.3f KiB/s)",
5817 duration_elapsed(&bench),
5818 duration_kbps(&bench, count * size));
5820 command_print(CMD_CTX, "Compare failed");
5821 binprint(CMD_CTX, "ref:", read_ref, num_bytes);
5822 binprint(CMD_CTX, "buf:", read_buf, num_bytes);
5834 target_free_working_area(target, wa);
5838 static const struct command_registration target_exec_command_handlers[] = {
5840 .name = "fast_load_image",
5841 .handler = handle_fast_load_image_command,
5842 .mode = COMMAND_ANY,
5843 .help = "Load image into server memory for later use by "
5844 "fast_load; primarily for profiling",
5845 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5846 "[min_address [max_length]]",
5849 .name = "fast_load",
5850 .handler = handle_fast_load_command,
5851 .mode = COMMAND_EXEC,
5852 .help = "loads active fast load image to current target "
5853 "- mainly for profiling purposes",
5858 .handler = handle_profile_command,
5859 .mode = COMMAND_EXEC,
5860 .usage = "seconds filename [start end]",
5861 .help = "profiling samples the CPU PC",
5863 /** @todo don't register virt2phys() unless target supports it */
5865 .name = "virt2phys",
5866 .handler = handle_virt2phys_command,
5867 .mode = COMMAND_ANY,
5868 .help = "translate a virtual address into a physical address",
5869 .usage = "virtual_address",
5873 .handler = handle_reg_command,
5874 .mode = COMMAND_EXEC,
5875 .help = "display (reread from target with \"force\") or set a register; "
5876 "with no arguments, displays all registers and their values",
5877 .usage = "[(register_number|register_name) [(value|'force')]]",
5881 .handler = handle_poll_command,
5882 .mode = COMMAND_EXEC,
5883 .help = "poll target state; or reconfigure background polling",
5884 .usage = "['on'|'off']",
5887 .name = "wait_halt",
5888 .handler = handle_wait_halt_command,
5889 .mode = COMMAND_EXEC,
5890 .help = "wait up to the specified number of milliseconds "
5891 "(default 5000) for a previously requested halt",
5892 .usage = "[milliseconds]",
5896 .handler = handle_halt_command,
5897 .mode = COMMAND_EXEC,
5898 .help = "request target to halt, then wait up to the specified"
5899 "number of milliseconds (default 5000) for it to complete",
5900 .usage = "[milliseconds]",
5904 .handler = handle_resume_command,
5905 .mode = COMMAND_EXEC,
5906 .help = "resume target execution from current PC or address",
5907 .usage = "[address]",
5911 .handler = handle_reset_command,
5912 .mode = COMMAND_EXEC,
5913 .usage = "[run|halt|init]",
5914 .help = "Reset all targets into the specified mode."
5915 "Default reset mode is run, if not given.",
5918 .name = "soft_reset_halt",
5919 .handler = handle_soft_reset_halt_command,
5920 .mode = COMMAND_EXEC,
5922 .help = "halt the target and do a soft reset",
5926 .handler = handle_step_command,
5927 .mode = COMMAND_EXEC,
5928 .help = "step one instruction from current PC or address",
5929 .usage = "[address]",
5933 .handler = handle_md_command,
5934 .mode = COMMAND_EXEC,
5935 .help = "display memory words",
5936 .usage = "['phys'] address [count]",
5940 .handler = handle_md_command,
5941 .mode = COMMAND_EXEC,
5942 .help = "display memory half-words",
5943 .usage = "['phys'] address [count]",
5947 .handler = handle_md_command,
5948 .mode = COMMAND_EXEC,
5949 .help = "display memory bytes",
5950 .usage = "['phys'] address [count]",
5954 .handler = handle_mw_command,
5955 .mode = COMMAND_EXEC,
5956 .help = "write memory word",
5957 .usage = "['phys'] address value [count]",
5961 .handler = handle_mw_command,
5962 .mode = COMMAND_EXEC,
5963 .help = "write memory half-word",
5964 .usage = "['phys'] address value [count]",
5968 .handler = handle_mw_command,
5969 .mode = COMMAND_EXEC,
5970 .help = "write memory byte",
5971 .usage = "['phys'] address value [count]",
5975 .handler = handle_bp_command,
5976 .mode = COMMAND_EXEC,
5977 .help = "list or set hardware or software breakpoint",
5978 .usage = "<address> [<asid>]<length> ['hw'|'hw_ctx']",
5982 .handler = handle_rbp_command,
5983 .mode = COMMAND_EXEC,
5984 .help = "remove breakpoint",
5989 .handler = handle_wp_command,
5990 .mode = COMMAND_EXEC,
5991 .help = "list (no params) or create watchpoints",
5992 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5996 .handler = handle_rwp_command,
5997 .mode = COMMAND_EXEC,
5998 .help = "remove watchpoint",
6002 .name = "load_image",
6003 .handler = handle_load_image_command,
6004 .mode = COMMAND_EXEC,
6005 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6006 "[min_address] [max_length]",
6009 .name = "dump_image",
6010 .handler = handle_dump_image_command,
6011 .mode = COMMAND_EXEC,
6012 .usage = "filename address size",
6015 .name = "verify_image",
6016 .handler = handle_verify_image_command,
6017 .mode = COMMAND_EXEC,
6018 .usage = "filename [offset [type]]",
6021 .name = "test_image",
6022 .handler = handle_test_image_command,
6023 .mode = COMMAND_EXEC,
6024 .usage = "filename [offset [type]]",
6027 .name = "mem2array",
6028 .mode = COMMAND_EXEC,
6029 .jim_handler = jim_mem2array,
6030 .help = "read 8/16/32 bit memory and return as a TCL array "
6031 "for script processing",
6032 .usage = "arrayname bitwidth address count",
6035 .name = "array2mem",
6036 .mode = COMMAND_EXEC,
6037 .jim_handler = jim_array2mem,
6038 .help = "convert a TCL array to memory locations "
6039 "and write the 8/16/32 bit values",
6040 .usage = "arrayname bitwidth address count",
6043 .name = "reset_nag",
6044 .handler = handle_target_reset_nag,
6045 .mode = COMMAND_ANY,
6046 .help = "Nag after each reset about options that could have been "
6047 "enabled to improve performance. ",
6048 .usage = "['enable'|'disable']",
6052 .handler = handle_ps_command,
6053 .mode = COMMAND_EXEC,
6054 .help = "list all tasks ",
6058 .name = "test_mem_access",
6059 .handler = handle_test_mem_access_command,
6060 .mode = COMMAND_EXEC,
6061 .help = "Test the target's memory access functions",
6065 COMMAND_REGISTRATION_DONE
6067 static int target_register_user_commands(struct command_context *cmd_ctx)
6069 int retval = ERROR_OK;
6070 retval = target_request_register_commands(cmd_ctx);
6071 if (retval != ERROR_OK)
6074 retval = trace_register_commands(cmd_ctx);
6075 if (retval != ERROR_OK)
6079 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);