target/target: Fix 'wp' command usage
[openocd.git] / src / target / target.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2
3 /***************************************************************************
4 * Copyright (C) 2005 by Dominic Rath *
5 * Dominic.Rath@gmx.de *
6 * *
7 * Copyright (C) 2007-2010 Øyvind Harboe *
8 * oyvind.harboe@zylin.com *
9 * *
10 * Copyright (C) 2008, Duane Ellis *
11 * openocd@duaneeellis.com *
12 * *
13 * Copyright (C) 2008 by Spencer Oliver *
14 * spen@spen-soft.co.uk *
15 * *
16 * Copyright (C) 2008 by Rick Altherr *
17 * kc8apf@kc8apf.net> *
18 * *
19 * Copyright (C) 2011 by Broadcom Corporation *
20 * Evan Hunter - ehunter@broadcom.com *
21 * *
22 * Copyright (C) ST-Ericsson SA 2011 *
23 * michel.jaouen@stericsson.com : smp minimum support *
24 * *
25 * Copyright (C) 2011 Andreas Fritiofson *
26 * andreas.fritiofson@gmail.com *
27 ***************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
32
33 #include <helper/align.h>
34 #include <helper/nvp.h>
35 #include <helper/time_support.h>
36 #include <jtag/jtag.h>
37 #include <flash/nor/core.h>
38
39 #include "target.h"
40 #include "target_type.h"
41 #include "target_request.h"
42 #include "breakpoints.h"
43 #include "register.h"
44 #include "trace.h"
45 #include "image.h"
46 #include "rtos/rtos.h"
47 #include "transport/transport.h"
48 #include "arm_cti.h"
49 #include "smp.h"
50 #include "semihosting_common.h"
51
52 /* default halt wait timeout (ms) */
53 #define DEFAULT_HALT_TIMEOUT 5000
54
55 static int target_read_buffer_default(struct target *target, target_addr_t address,
56 uint32_t count, uint8_t *buffer);
57 static int target_write_buffer_default(struct target *target, target_addr_t address,
58 uint32_t count, const uint8_t *buffer);
59 static int target_array2mem(Jim_Interp *interp, struct target *target,
60 int argc, Jim_Obj * const *argv);
61 static int target_mem2array(Jim_Interp *interp, struct target *target,
62 int argc, Jim_Obj * const *argv);
63 static int target_register_user_commands(struct command_context *cmd_ctx);
64 static int target_get_gdb_fileio_info_default(struct target *target,
65 struct gdb_fileio_info *fileio_info);
66 static int target_gdb_fileio_end_default(struct target *target, int retcode,
67 int fileio_errno, bool ctrl_c);
68
69 static struct target_type *target_types[] = {
70 &arm7tdmi_target,
71 &arm9tdmi_target,
72 &arm920t_target,
73 &arm720t_target,
74 &arm966e_target,
75 &arm946e_target,
76 &arm926ejs_target,
77 &fa526_target,
78 &feroceon_target,
79 &dragonite_target,
80 &xscale_target,
81 &xtensa_chip_target,
82 &cortexm_target,
83 &cortexa_target,
84 &cortexr4_target,
85 &arm11_target,
86 &ls1_sap_target,
87 &mips_m4k_target,
88 &avr_target,
89 &dsp563xx_target,
90 &dsp5680xx_target,
91 &testee_target,
92 &avr32_ap7k_target,
93 &hla_target,
94 &esp32_target,
95 &esp32s2_target,
96 &esp32s3_target,
97 &or1k_target,
98 &quark_x10xx_target,
99 &quark_d20xx_target,
100 &stm8_target,
101 &riscv_target,
102 &mem_ap_target,
103 &esirisc_target,
104 &arcv2_target,
105 &aarch64_target,
106 &armv8r_target,
107 &mips_mips64_target,
108 NULL,
109 };
110
111 struct target *all_targets;
112 static struct target_event_callback *target_event_callbacks;
113 static struct target_timer_callback *target_timer_callbacks;
114 static int64_t target_timer_next_event_value;
115 static LIST_HEAD(target_reset_callback_list);
116 static LIST_HEAD(target_trace_callback_list);
117 static const int polling_interval = TARGET_DEFAULT_POLLING_INTERVAL;
118 static LIST_HEAD(empty_smp_targets);
119
120 enum nvp_assert {
121 NVP_DEASSERT,
122 NVP_ASSERT,
123 };
124
125 static const struct nvp nvp_assert[] = {
126 { .name = "assert", NVP_ASSERT },
127 { .name = "deassert", NVP_DEASSERT },
128 { .name = "T", NVP_ASSERT },
129 { .name = "F", NVP_DEASSERT },
130 { .name = "t", NVP_ASSERT },
131 { .name = "f", NVP_DEASSERT },
132 { .name = NULL, .value = -1 }
133 };
134
135 static const struct nvp nvp_error_target[] = {
136 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
137 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
138 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
139 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
140 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
141 { .value = ERROR_TARGET_UNALIGNED_ACCESS, .name = "err-unaligned-access" },
142 { .value = ERROR_TARGET_DATA_ABORT, .name = "err-data-abort" },
143 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE, .name = "err-resource-not-available" },
144 { .value = ERROR_TARGET_TRANSLATION_FAULT, .name = "err-translation-fault" },
145 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
146 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
147 { .value = -1, .name = NULL }
148 };
149
150 static const char *target_strerror_safe(int err)
151 {
152 const struct nvp *n;
153
154 n = nvp_value2name(nvp_error_target, err);
155 if (!n->name)
156 return "unknown";
157 else
158 return n->name;
159 }
160
161 static const struct jim_nvp nvp_target_event[] = {
162
163 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
164 { .value = TARGET_EVENT_HALTED, .name = "halted" },
165 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
166 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
167 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
168 { .value = TARGET_EVENT_STEP_START, .name = "step-start" },
169 { .value = TARGET_EVENT_STEP_END, .name = "step-end" },
170
171 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
172 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
173
174 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
175 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
176 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
177 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
178 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
179 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
180 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
181 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
182
183 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
184 { .value = TARGET_EVENT_EXAMINE_FAIL, .name = "examine-fail" },
185 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
186
187 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
188 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
189
190 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
191 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
192
193 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
194 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END, .name = "gdb-flash-write-end" },
195
196 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
197 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END, .name = "gdb-flash-erase-end" },
198
199 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
200
201 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X100, .name = "semihosting-user-cmd-0x100" },
202 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X101, .name = "semihosting-user-cmd-0x101" },
203 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X102, .name = "semihosting-user-cmd-0x102" },
204 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X103, .name = "semihosting-user-cmd-0x103" },
205 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X104, .name = "semihosting-user-cmd-0x104" },
206 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X105, .name = "semihosting-user-cmd-0x105" },
207 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X106, .name = "semihosting-user-cmd-0x106" },
208 { .value = TARGET_EVENT_SEMIHOSTING_USER_CMD_0X107, .name = "semihosting-user-cmd-0x107" },
209
210 { .name = NULL, .value = -1 }
211 };
212
213 static const struct nvp nvp_target_state[] = {
214 { .name = "unknown", .value = TARGET_UNKNOWN },
215 { .name = "running", .value = TARGET_RUNNING },
216 { .name = "halted", .value = TARGET_HALTED },
217 { .name = "reset", .value = TARGET_RESET },
218 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
219 { .name = NULL, .value = -1 },
220 };
221
222 static const struct nvp nvp_target_debug_reason[] = {
223 { .name = "debug-request", .value = DBG_REASON_DBGRQ },
224 { .name = "breakpoint", .value = DBG_REASON_BREAKPOINT },
225 { .name = "watchpoint", .value = DBG_REASON_WATCHPOINT },
226 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
227 { .name = "single-step", .value = DBG_REASON_SINGLESTEP },
228 { .name = "target-not-halted", .value = DBG_REASON_NOTHALTED },
229 { .name = "program-exit", .value = DBG_REASON_EXIT },
230 { .name = "exception-catch", .value = DBG_REASON_EXC_CATCH },
231 { .name = "undefined", .value = DBG_REASON_UNDEFINED },
232 { .name = NULL, .value = -1 },
233 };
234
235 static const struct jim_nvp nvp_target_endian[] = {
236 { .name = "big", .value = TARGET_BIG_ENDIAN },
237 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
238 { .name = "be", .value = TARGET_BIG_ENDIAN },
239 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
240 { .name = NULL, .value = -1 },
241 };
242
243 static const struct nvp nvp_reset_modes[] = {
244 { .name = "unknown", .value = RESET_UNKNOWN },
245 { .name = "run", .value = RESET_RUN },
246 { .name = "halt", .value = RESET_HALT },
247 { .name = "init", .value = RESET_INIT },
248 { .name = NULL, .value = -1 },
249 };
250
251 const char *debug_reason_name(struct target *t)
252 {
253 const char *cp;
254
255 cp = nvp_value2name(nvp_target_debug_reason,
256 t->debug_reason)->name;
257 if (!cp) {
258 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
259 cp = "(*BUG*unknown*BUG*)";
260 }
261 return cp;
262 }
263
264 const char *target_state_name(struct target *t)
265 {
266 const char *cp;
267 cp = nvp_value2name(nvp_target_state, t->state)->name;
268 if (!cp) {
269 LOG_ERROR("Invalid target state: %d", (int)(t->state));
270 cp = "(*BUG*unknown*BUG*)";
271 }
272
273 if (!target_was_examined(t) && t->defer_examine)
274 cp = "examine deferred";
275
276 return cp;
277 }
278
279 const char *target_event_name(enum target_event event)
280 {
281 const char *cp;
282 cp = jim_nvp_value2name_simple(nvp_target_event, event)->name;
283 if (!cp) {
284 LOG_ERROR("Invalid target event: %d", (int)(event));
285 cp = "(*BUG*unknown*BUG*)";
286 }
287 return cp;
288 }
289
290 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
291 {
292 const char *cp;
293 cp = nvp_value2name(nvp_reset_modes, reset_mode)->name;
294 if (!cp) {
295 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
296 cp = "(*BUG*unknown*BUG*)";
297 }
298 return cp;
299 }
300
301 static void append_to_list_all_targets(struct target *target)
302 {
303 struct target **t = &all_targets;
304
305 while (*t)
306 t = &((*t)->next);
307 *t = target;
308 }
309
310 /* read a uint64_t from a buffer in target memory endianness */
311 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
312 {
313 if (target->endianness == TARGET_LITTLE_ENDIAN)
314 return le_to_h_u64(buffer);
315 else
316 return be_to_h_u64(buffer);
317 }
318
319 /* read a uint32_t from a buffer in target memory endianness */
320 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
321 {
322 if (target->endianness == TARGET_LITTLE_ENDIAN)
323 return le_to_h_u32(buffer);
324 else
325 return be_to_h_u32(buffer);
326 }
327
328 /* read a uint24_t from a buffer in target memory endianness */
329 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
330 {
331 if (target->endianness == TARGET_LITTLE_ENDIAN)
332 return le_to_h_u24(buffer);
333 else
334 return be_to_h_u24(buffer);
335 }
336
337 /* read a uint16_t from a buffer in target memory endianness */
338 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
339 {
340 if (target->endianness == TARGET_LITTLE_ENDIAN)
341 return le_to_h_u16(buffer);
342 else
343 return be_to_h_u16(buffer);
344 }
345
346 /* write a uint64_t to a buffer in target memory endianness */
347 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
348 {
349 if (target->endianness == TARGET_LITTLE_ENDIAN)
350 h_u64_to_le(buffer, value);
351 else
352 h_u64_to_be(buffer, value);
353 }
354
355 /* write a uint32_t to a buffer in target memory endianness */
356 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
357 {
358 if (target->endianness == TARGET_LITTLE_ENDIAN)
359 h_u32_to_le(buffer, value);
360 else
361 h_u32_to_be(buffer, value);
362 }
363
364 /* write a uint24_t to a buffer in target memory endianness */
365 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
366 {
367 if (target->endianness == TARGET_LITTLE_ENDIAN)
368 h_u24_to_le(buffer, value);
369 else
370 h_u24_to_be(buffer, value);
371 }
372
373 /* write a uint16_t to a buffer in target memory endianness */
374 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
375 {
376 if (target->endianness == TARGET_LITTLE_ENDIAN)
377 h_u16_to_le(buffer, value);
378 else
379 h_u16_to_be(buffer, value);
380 }
381
382 /* write a uint8_t to a buffer in target memory endianness */
383 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
384 {
385 *buffer = value;
386 }
387
388 /* write a uint64_t array to a buffer in target memory endianness */
389 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
390 {
391 uint32_t i;
392 for (i = 0; i < count; i++)
393 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
394 }
395
396 /* write a uint32_t array to a buffer in target memory endianness */
397 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
398 {
399 uint32_t i;
400 for (i = 0; i < count; i++)
401 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
402 }
403
404 /* write a uint16_t array to a buffer in target memory endianness */
405 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
406 {
407 uint32_t i;
408 for (i = 0; i < count; i++)
409 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
410 }
411
412 /* write a uint64_t array to a buffer in target memory endianness */
413 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
414 {
415 uint32_t i;
416 for (i = 0; i < count; i++)
417 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
418 }
419
420 /* write a uint32_t array to a buffer in target memory endianness */
421 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
422 {
423 uint32_t i;
424 for (i = 0; i < count; i++)
425 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
426 }
427
428 /* write a uint16_t array to a buffer in target memory endianness */
429 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
430 {
431 uint32_t i;
432 for (i = 0; i < count; i++)
433 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
434 }
435
436 /* return a pointer to a configured target; id is name or index in all_targets */
437 struct target *get_target(const char *id)
438 {
439 struct target *target;
440
441 /* try as tcltarget name */
442 for (target = all_targets; target; target = target->next) {
443 if (!target_name(target))
444 continue;
445 if (strcmp(id, target_name(target)) == 0)
446 return target;
447 }
448
449 /* try as index */
450 unsigned int index, counter;
451 if (parse_uint(id, &index) != ERROR_OK)
452 return NULL;
453
454 for (target = all_targets, counter = index;
455 target && counter;
456 target = target->next, --counter)
457 ;
458
459 return target;
460 }
461
462 struct target *get_current_target(struct command_context *cmd_ctx)
463 {
464 struct target *target = get_current_target_or_null(cmd_ctx);
465
466 if (!target) {
467 LOG_ERROR("BUG: current_target out of bounds");
468 exit(-1);
469 }
470
471 return target;
472 }
473
474 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
475 {
476 return cmd_ctx->current_target_override
477 ? cmd_ctx->current_target_override
478 : cmd_ctx->current_target;
479 }
480
481 int target_poll(struct target *target)
482 {
483 int retval;
484
485 /* We can't poll until after examine */
486 if (!target_was_examined(target)) {
487 /* Fail silently lest we pollute the log */
488 return ERROR_FAIL;
489 }
490
491 retval = target->type->poll(target);
492 if (retval != ERROR_OK)
493 return retval;
494
495 if (target->halt_issued) {
496 if (target->state == TARGET_HALTED)
497 target->halt_issued = false;
498 else {
499 int64_t t = timeval_ms() - target->halt_issued_time;
500 if (t > DEFAULT_HALT_TIMEOUT) {
501 target->halt_issued = false;
502 LOG_INFO("Halt timed out, wake up GDB.");
503 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
504 }
505 }
506 }
507
508 return ERROR_OK;
509 }
510
511 int target_halt(struct target *target)
512 {
513 int retval;
514 /* We can't poll until after examine */
515 if (!target_was_examined(target)) {
516 LOG_ERROR("Target not examined yet");
517 return ERROR_FAIL;
518 }
519
520 retval = target->type->halt(target);
521 if (retval != ERROR_OK)
522 return retval;
523
524 target->halt_issued = true;
525 target->halt_issued_time = timeval_ms();
526
527 return ERROR_OK;
528 }
529
530 /**
531 * Make the target (re)start executing using its saved execution
532 * context (possibly with some modifications).
533 *
534 * @param target Which target should start executing.
535 * @param current True to use the target's saved program counter instead
536 * of the address parameter
537 * @param address Optionally used as the program counter.
538 * @param handle_breakpoints True iff breakpoints at the resumption PC
539 * should be skipped. (For example, maybe execution was stopped by
540 * such a breakpoint, in which case it would be counterproductive to
541 * let it re-trigger.
542 * @param debug_execution False if all working areas allocated by OpenOCD
543 * should be released and/or restored to their original contents.
544 * (This would for example be true to run some downloaded "helper"
545 * algorithm code, which resides in one such working buffer and uses
546 * another for data storage.)
547 *
548 * @todo Resolve the ambiguity about what the "debug_execution" flag
549 * signifies. For example, Target implementations don't agree on how
550 * it relates to invalidation of the register cache, or to whether
551 * breakpoints and watchpoints should be enabled. (It would seem wrong
552 * to enable breakpoints when running downloaded "helper" algorithms
553 * (debug_execution true), since the breakpoints would be set to match
554 * target firmware being debugged, not the helper algorithm.... and
555 * enabling them could cause such helpers to malfunction (for example,
556 * by overwriting data with a breakpoint instruction. On the other
557 * hand the infrastructure for running such helpers might use this
558 * procedure but rely on hardware breakpoint to detect termination.)
559 */
560 int target_resume(struct target *target, int current, target_addr_t address,
561 int handle_breakpoints, int debug_execution)
562 {
563 int retval;
564
565 /* We can't poll until after examine */
566 if (!target_was_examined(target)) {
567 LOG_ERROR("Target not examined yet");
568 return ERROR_FAIL;
569 }
570
571 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
572
573 /* note that resume *must* be asynchronous. The CPU can halt before
574 * we poll. The CPU can even halt at the current PC as a result of
575 * a software breakpoint being inserted by (a bug?) the application.
576 */
577 /*
578 * resume() triggers the event 'resumed'. The execution of TCL commands
579 * in the event handler causes the polling of targets. If the target has
580 * already halted for a breakpoint, polling will run the 'halted' event
581 * handler before the pending 'resumed' handler.
582 * Disable polling during resume() to guarantee the execution of handlers
583 * in the correct order.
584 */
585 bool save_poll_mask = jtag_poll_mask();
586 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
587 jtag_poll_unmask(save_poll_mask);
588
589 if (retval != ERROR_OK)
590 return retval;
591
592 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
593
594 return retval;
595 }
596
597 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
598 {
599 char buf[100];
600 int retval;
601 const struct nvp *n;
602 n = nvp_value2name(nvp_reset_modes, reset_mode);
603 if (!n->name) {
604 LOG_ERROR("invalid reset mode");
605 return ERROR_FAIL;
606 }
607
608 struct target *target;
609 for (target = all_targets; target; target = target->next)
610 target_call_reset_callbacks(target, reset_mode);
611
612 /* disable polling during reset to make reset event scripts
613 * more predictable, i.e. dr/irscan & pathmove in events will
614 * not have JTAG operations injected into the middle of a sequence.
615 */
616 bool save_poll_mask = jtag_poll_mask();
617
618 sprintf(buf, "ocd_process_reset %s", n->name);
619 retval = Jim_Eval(cmd->ctx->interp, buf);
620
621 jtag_poll_unmask(save_poll_mask);
622
623 if (retval != JIM_OK) {
624 Jim_MakeErrorMessage(cmd->ctx->interp);
625 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
626 return ERROR_FAIL;
627 }
628
629 /* We want any events to be processed before the prompt */
630 retval = target_call_timer_callbacks_now();
631
632 for (target = all_targets; target; target = target->next) {
633 target->type->check_reset(target);
634 target->running_alg = false;
635 }
636
637 return retval;
638 }
639
640 static int identity_virt2phys(struct target *target,
641 target_addr_t virtual, target_addr_t *physical)
642 {
643 *physical = virtual;
644 return ERROR_OK;
645 }
646
647 static int no_mmu(struct target *target, int *enabled)
648 {
649 *enabled = 0;
650 return ERROR_OK;
651 }
652
653 /**
654 * Reset the @c examined flag for the given target.
655 * Pure paranoia -- targets are zeroed on allocation.
656 */
657 static inline void target_reset_examined(struct target *target)
658 {
659 target->examined = false;
660 }
661
662 static int default_examine(struct target *target)
663 {
664 target_set_examined(target);
665 return ERROR_OK;
666 }
667
668 /* no check by default */
669 static int default_check_reset(struct target *target)
670 {
671 return ERROR_OK;
672 }
673
674 /* Equivalent Tcl code arp_examine_one is in src/target/startup.tcl
675 * Keep in sync */
676 int target_examine_one(struct target *target)
677 {
678 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
679
680 int retval = target->type->examine(target);
681 if (retval != ERROR_OK) {
682 target_reset_examined(target);
683 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_FAIL);
684 return retval;
685 }
686
687 target_set_examined(target);
688 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
689
690 return ERROR_OK;
691 }
692
693 static int jtag_enable_callback(enum jtag_event event, void *priv)
694 {
695 struct target *target = priv;
696
697 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
698 return ERROR_OK;
699
700 jtag_unregister_event_callback(jtag_enable_callback, target);
701
702 return target_examine_one(target);
703 }
704
705 /* Targets that correctly implement init + examine, i.e.
706 * no communication with target during init:
707 *
708 * XScale
709 */
710 int target_examine(void)
711 {
712 int retval = ERROR_OK;
713 struct target *target;
714
715 for (target = all_targets; target; target = target->next) {
716 /* defer examination, but don't skip it */
717 if (!target->tap->enabled) {
718 jtag_register_event_callback(jtag_enable_callback,
719 target);
720 continue;
721 }
722
723 if (target->defer_examine)
724 continue;
725
726 int retval2 = target_examine_one(target);
727 if (retval2 != ERROR_OK) {
728 LOG_WARNING("target %s examination failed", target_name(target));
729 retval = retval2;
730 }
731 }
732 return retval;
733 }
734
735 const char *target_type_name(struct target *target)
736 {
737 return target->type->name;
738 }
739
740 static int target_soft_reset_halt(struct target *target)
741 {
742 if (!target_was_examined(target)) {
743 LOG_ERROR("Target not examined yet");
744 return ERROR_FAIL;
745 }
746 if (!target->type->soft_reset_halt) {
747 LOG_ERROR("Target %s does not support soft_reset_halt",
748 target_name(target));
749 return ERROR_FAIL;
750 }
751 return target->type->soft_reset_halt(target);
752 }
753
754 /**
755 * Downloads a target-specific native code algorithm to the target,
756 * and executes it. * Note that some targets may need to set up, enable,
757 * and tear down a breakpoint (hard or * soft) to detect algorithm
758 * termination, while others may support lower overhead schemes where
759 * soft breakpoints embedded in the algorithm automatically terminate the
760 * algorithm.
761 *
762 * @param target used to run the algorithm
763 * @param num_mem_params
764 * @param mem_params
765 * @param num_reg_params
766 * @param reg_param
767 * @param entry_point
768 * @param exit_point
769 * @param timeout_ms
770 * @param arch_info target-specific description of the algorithm.
771 */
772 int target_run_algorithm(struct target *target,
773 int num_mem_params, struct mem_param *mem_params,
774 int num_reg_params, struct reg_param *reg_param,
775 target_addr_t entry_point, target_addr_t exit_point,
776 unsigned int timeout_ms, void *arch_info)
777 {
778 int retval = ERROR_FAIL;
779
780 if (!target_was_examined(target)) {
781 LOG_ERROR("Target not examined yet");
782 goto done;
783 }
784 if (!target->type->run_algorithm) {
785 LOG_ERROR("Target type '%s' does not support %s",
786 target_type_name(target), __func__);
787 goto done;
788 }
789
790 target->running_alg = true;
791 retval = target->type->run_algorithm(target,
792 num_mem_params, mem_params,
793 num_reg_params, reg_param,
794 entry_point, exit_point, timeout_ms, arch_info);
795 target->running_alg = false;
796
797 done:
798 return retval;
799 }
800
801 /**
802 * Executes a target-specific native code algorithm and leaves it running.
803 *
804 * @param target used to run the algorithm
805 * @param num_mem_params
806 * @param mem_params
807 * @param num_reg_params
808 * @param reg_params
809 * @param entry_point
810 * @param exit_point
811 * @param arch_info target-specific description of the algorithm.
812 */
813 int target_start_algorithm(struct target *target,
814 int num_mem_params, struct mem_param *mem_params,
815 int num_reg_params, struct reg_param *reg_params,
816 target_addr_t entry_point, target_addr_t exit_point,
817 void *arch_info)
818 {
819 int retval = ERROR_FAIL;
820
821 if (!target_was_examined(target)) {
822 LOG_ERROR("Target not examined yet");
823 goto done;
824 }
825 if (!target->type->start_algorithm) {
826 LOG_ERROR("Target type '%s' does not support %s",
827 target_type_name(target), __func__);
828 goto done;
829 }
830 if (target->running_alg) {
831 LOG_ERROR("Target is already running an algorithm");
832 goto done;
833 }
834
835 target->running_alg = true;
836 retval = target->type->start_algorithm(target,
837 num_mem_params, mem_params,
838 num_reg_params, reg_params,
839 entry_point, exit_point, arch_info);
840
841 done:
842 return retval;
843 }
844
845 /**
846 * Waits for an algorithm started with target_start_algorithm() to complete.
847 *
848 * @param target used to run the algorithm
849 * @param num_mem_params
850 * @param mem_params
851 * @param num_reg_params
852 * @param reg_params
853 * @param exit_point
854 * @param timeout_ms
855 * @param arch_info target-specific description of the algorithm.
856 */
857 int target_wait_algorithm(struct target *target,
858 int num_mem_params, struct mem_param *mem_params,
859 int num_reg_params, struct reg_param *reg_params,
860 target_addr_t exit_point, unsigned int timeout_ms,
861 void *arch_info)
862 {
863 int retval = ERROR_FAIL;
864
865 if (!target->type->wait_algorithm) {
866 LOG_ERROR("Target type '%s' does not support %s",
867 target_type_name(target), __func__);
868 goto done;
869 }
870 if (!target->running_alg) {
871 LOG_ERROR("Target is not running an algorithm");
872 goto done;
873 }
874
875 retval = target->type->wait_algorithm(target,
876 num_mem_params, mem_params,
877 num_reg_params, reg_params,
878 exit_point, timeout_ms, arch_info);
879 if (retval != ERROR_TARGET_TIMEOUT)
880 target->running_alg = false;
881
882 done:
883 return retval;
884 }
885
886 /**
887 * Streams data to a circular buffer on target intended for consumption by code
888 * running asynchronously on target.
889 *
890 * This is intended for applications where target-specific native code runs
891 * on the target, receives data from the circular buffer, does something with
892 * it (most likely writing it to a flash memory), and advances the circular
893 * buffer pointer.
894 *
895 * This assumes that the helper algorithm has already been loaded to the target,
896 * but has not been started yet. Given memory and register parameters are passed
897 * to the algorithm.
898 *
899 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
900 * following format:
901 *
902 * [buffer_start + 0, buffer_start + 4):
903 * Write Pointer address (aka head). Written and updated by this
904 * routine when new data is written to the circular buffer.
905 * [buffer_start + 4, buffer_start + 8):
906 * Read Pointer address (aka tail). Updated by code running on the
907 * target after it consumes data.
908 * [buffer_start + 8, buffer_start + buffer_size):
909 * Circular buffer contents.
910 *
911 * See contrib/loaders/flash/stm32f1x.S for an example.
912 *
913 * @param target used to run the algorithm
914 * @param buffer address on the host where data to be sent is located
915 * @param count number of blocks to send
916 * @param block_size size in bytes of each block
917 * @param num_mem_params count of memory-based params to pass to algorithm
918 * @param mem_params memory-based params to pass to algorithm
919 * @param num_reg_params count of register-based params to pass to algorithm
920 * @param reg_params memory-based params to pass to algorithm
921 * @param buffer_start address on the target of the circular buffer structure
922 * @param buffer_size size of the circular buffer structure
923 * @param entry_point address on the target to execute to start the algorithm
924 * @param exit_point address at which to set a breakpoint to catch the
925 * end of the algorithm; can be 0 if target triggers a breakpoint itself
926 * @param arch_info
927 */
928
929 int target_run_flash_async_algorithm(struct target *target,
930 const uint8_t *buffer, uint32_t count, int block_size,
931 int num_mem_params, struct mem_param *mem_params,
932 int num_reg_params, struct reg_param *reg_params,
933 uint32_t buffer_start, uint32_t buffer_size,
934 uint32_t entry_point, uint32_t exit_point, void *arch_info)
935 {
936 int retval;
937 int timeout = 0;
938
939 const uint8_t *buffer_orig = buffer;
940
941 /* Set up working area. First word is write pointer, second word is read pointer,
942 * rest is fifo data area. */
943 uint32_t wp_addr = buffer_start;
944 uint32_t rp_addr = buffer_start + 4;
945 uint32_t fifo_start_addr = buffer_start + 8;
946 uint32_t fifo_end_addr = buffer_start + buffer_size;
947
948 uint32_t wp = fifo_start_addr;
949 uint32_t rp = fifo_start_addr;
950
951 /* validate block_size is 2^n */
952 assert(IS_PWR_OF_2(block_size));
953
954 retval = target_write_u32(target, wp_addr, wp);
955 if (retval != ERROR_OK)
956 return retval;
957 retval = target_write_u32(target, rp_addr, rp);
958 if (retval != ERROR_OK)
959 return retval;
960
961 /* Start up algorithm on target and let it idle while writing the first chunk */
962 retval = target_start_algorithm(target, num_mem_params, mem_params,
963 num_reg_params, reg_params,
964 entry_point,
965 exit_point,
966 arch_info);
967
968 if (retval != ERROR_OK) {
969 LOG_ERROR("error starting target flash write algorithm");
970 return retval;
971 }
972
973 while (count > 0) {
974
975 retval = target_read_u32(target, rp_addr, &rp);
976 if (retval != ERROR_OK) {
977 LOG_ERROR("failed to get read pointer");
978 break;
979 }
980
981 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
982 (size_t) (buffer - buffer_orig), count, wp, rp);
983
984 if (rp == 0) {
985 LOG_ERROR("flash write algorithm aborted by target");
986 retval = ERROR_FLASH_OPERATION_FAILED;
987 break;
988 }
989
990 if (!IS_ALIGNED(rp - fifo_start_addr, block_size) || rp < fifo_start_addr || rp >= fifo_end_addr) {
991 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
992 break;
993 }
994
995 /* Count the number of bytes available in the fifo without
996 * crossing the wrap around. Make sure to not fill it completely,
997 * because that would make wp == rp and that's the empty condition. */
998 uint32_t thisrun_bytes;
999 if (rp > wp)
1000 thisrun_bytes = rp - wp - block_size;
1001 else if (rp > fifo_start_addr)
1002 thisrun_bytes = fifo_end_addr - wp;
1003 else
1004 thisrun_bytes = fifo_end_addr - wp - block_size;
1005
1006 if (thisrun_bytes == 0) {
1007 /* Throttle polling a bit if transfer is (much) faster than flash
1008 * programming. The exact delay shouldn't matter as long as it's
1009 * less than buffer size / flash speed. This is very unlikely to
1010 * run when using high latency connections such as USB. */
1011 alive_sleep(2);
1012
1013 /* to stop an infinite loop on some targets check and increment a timeout
1014 * this issue was observed on a stellaris using the new ICDI interface */
1015 if (timeout++ >= 2500) {
1016 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1017 return ERROR_FLASH_OPERATION_FAILED;
1018 }
1019 continue;
1020 }
1021
1022 /* reset our timeout */
1023 timeout = 0;
1024
1025 /* Limit to the amount of data we actually want to write */
1026 if (thisrun_bytes > count * block_size)
1027 thisrun_bytes = count * block_size;
1028
1029 /* Force end of large blocks to be word aligned */
1030 if (thisrun_bytes >= 16)
1031 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1032
1033 /* Write data to fifo */
1034 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1035 if (retval != ERROR_OK)
1036 break;
1037
1038 /* Update counters and wrap write pointer */
1039 buffer += thisrun_bytes;
1040 count -= thisrun_bytes / block_size;
1041 wp += thisrun_bytes;
1042 if (wp >= fifo_end_addr)
1043 wp = fifo_start_addr;
1044
1045 /* Store updated write pointer to target */
1046 retval = target_write_u32(target, wp_addr, wp);
1047 if (retval != ERROR_OK)
1048 break;
1049
1050 /* Avoid GDB timeouts */
1051 keep_alive();
1052 }
1053
1054 if (retval != ERROR_OK) {
1055 /* abort flash write algorithm on target */
1056 target_write_u32(target, wp_addr, 0);
1057 }
1058
1059 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1060 num_reg_params, reg_params,
1061 exit_point,
1062 10000,
1063 arch_info);
1064
1065 if (retval2 != ERROR_OK) {
1066 LOG_ERROR("error waiting for target flash write algorithm");
1067 retval = retval2;
1068 }
1069
1070 if (retval == ERROR_OK) {
1071 /* check if algorithm set rp = 0 after fifo writer loop finished */
1072 retval = target_read_u32(target, rp_addr, &rp);
1073 if (retval == ERROR_OK && rp == 0) {
1074 LOG_ERROR("flash write algorithm aborted by target");
1075 retval = ERROR_FLASH_OPERATION_FAILED;
1076 }
1077 }
1078
1079 return retval;
1080 }
1081
1082 int target_run_read_async_algorithm(struct target *target,
1083 uint8_t *buffer, uint32_t count, int block_size,
1084 int num_mem_params, struct mem_param *mem_params,
1085 int num_reg_params, struct reg_param *reg_params,
1086 uint32_t buffer_start, uint32_t buffer_size,
1087 uint32_t entry_point, uint32_t exit_point, void *arch_info)
1088 {
1089 int retval;
1090 int timeout = 0;
1091
1092 const uint8_t *buffer_orig = buffer;
1093
1094 /* Set up working area. First word is write pointer, second word is read pointer,
1095 * rest is fifo data area. */
1096 uint32_t wp_addr = buffer_start;
1097 uint32_t rp_addr = buffer_start + 4;
1098 uint32_t fifo_start_addr = buffer_start + 8;
1099 uint32_t fifo_end_addr = buffer_start + buffer_size;
1100
1101 uint32_t wp = fifo_start_addr;
1102 uint32_t rp = fifo_start_addr;
1103
1104 /* validate block_size is 2^n */
1105 assert(IS_PWR_OF_2(block_size));
1106
1107 retval = target_write_u32(target, wp_addr, wp);
1108 if (retval != ERROR_OK)
1109 return retval;
1110 retval = target_write_u32(target, rp_addr, rp);
1111 if (retval != ERROR_OK)
1112 return retval;
1113
1114 /* Start up algorithm on target */
1115 retval = target_start_algorithm(target, num_mem_params, mem_params,
1116 num_reg_params, reg_params,
1117 entry_point,
1118 exit_point,
1119 arch_info);
1120
1121 if (retval != ERROR_OK) {
1122 LOG_ERROR("error starting target flash read algorithm");
1123 return retval;
1124 }
1125
1126 while (count > 0) {
1127 retval = target_read_u32(target, wp_addr, &wp);
1128 if (retval != ERROR_OK) {
1129 LOG_ERROR("failed to get write pointer");
1130 break;
1131 }
1132
1133 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
1134 (size_t)(buffer - buffer_orig), count, wp, rp);
1135
1136 if (wp == 0) {
1137 LOG_ERROR("flash read algorithm aborted by target");
1138 retval = ERROR_FLASH_OPERATION_FAILED;
1139 break;
1140 }
1141
1142 if (!IS_ALIGNED(wp - fifo_start_addr, block_size) || wp < fifo_start_addr || wp >= fifo_end_addr) {
1143 LOG_ERROR("corrupted fifo write pointer 0x%" PRIx32, wp);
1144 break;
1145 }
1146
1147 /* Count the number of bytes available in the fifo without
1148 * crossing the wrap around. */
1149 uint32_t thisrun_bytes;
1150 if (wp >= rp)
1151 thisrun_bytes = wp - rp;
1152 else
1153 thisrun_bytes = fifo_end_addr - rp;
1154
1155 if (thisrun_bytes == 0) {
1156 /* Throttle polling a bit if transfer is (much) faster than flash
1157 * reading. The exact delay shouldn't matter as long as it's
1158 * less than buffer size / flash speed. This is very unlikely to
1159 * run when using high latency connections such as USB. */
1160 alive_sleep(2);
1161
1162 /* to stop an infinite loop on some targets check and increment a timeout
1163 * this issue was observed on a stellaris using the new ICDI interface */
1164 if (timeout++ >= 2500) {
1165 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1166 return ERROR_FLASH_OPERATION_FAILED;
1167 }
1168 continue;
1169 }
1170
1171 /* Reset our timeout */
1172 timeout = 0;
1173
1174 /* Limit to the amount of data we actually want to read */
1175 if (thisrun_bytes > count * block_size)
1176 thisrun_bytes = count * block_size;
1177
1178 /* Force end of large blocks to be word aligned */
1179 if (thisrun_bytes >= 16)
1180 thisrun_bytes -= (rp + thisrun_bytes) & 0x03;
1181
1182 /* Read data from fifo */
1183 retval = target_read_buffer(target, rp, thisrun_bytes, buffer);
1184 if (retval != ERROR_OK)
1185 break;
1186
1187 /* Update counters and wrap write pointer */
1188 buffer += thisrun_bytes;
1189 count -= thisrun_bytes / block_size;
1190 rp += thisrun_bytes;
1191 if (rp >= fifo_end_addr)
1192 rp = fifo_start_addr;
1193
1194 /* Store updated write pointer to target */
1195 retval = target_write_u32(target, rp_addr, rp);
1196 if (retval != ERROR_OK)
1197 break;
1198
1199 /* Avoid GDB timeouts */
1200 keep_alive();
1201
1202 }
1203
1204 if (retval != ERROR_OK) {
1205 /* abort flash write algorithm on target */
1206 target_write_u32(target, rp_addr, 0);
1207 }
1208
1209 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1210 num_reg_params, reg_params,
1211 exit_point,
1212 10000,
1213 arch_info);
1214
1215 if (retval2 != ERROR_OK) {
1216 LOG_ERROR("error waiting for target flash write algorithm");
1217 retval = retval2;
1218 }
1219
1220 if (retval == ERROR_OK) {
1221 /* check if algorithm set wp = 0 after fifo writer loop finished */
1222 retval = target_read_u32(target, wp_addr, &wp);
1223 if (retval == ERROR_OK && wp == 0) {
1224 LOG_ERROR("flash read algorithm aborted by target");
1225 retval = ERROR_FLASH_OPERATION_FAILED;
1226 }
1227 }
1228
1229 return retval;
1230 }
1231
1232 int target_read_memory(struct target *target,
1233 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1234 {
1235 if (!target_was_examined(target)) {
1236 LOG_ERROR("Target not examined yet");
1237 return ERROR_FAIL;
1238 }
1239 if (!target->type->read_memory) {
1240 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1241 return ERROR_FAIL;
1242 }
1243 return target->type->read_memory(target, address, size, count, buffer);
1244 }
1245
1246 int target_read_phys_memory(struct target *target,
1247 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1248 {
1249 if (!target_was_examined(target)) {
1250 LOG_ERROR("Target not examined yet");
1251 return ERROR_FAIL;
1252 }
1253 if (!target->type->read_phys_memory) {
1254 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1255 return ERROR_FAIL;
1256 }
1257 return target->type->read_phys_memory(target, address, size, count, buffer);
1258 }
1259
1260 int target_write_memory(struct target *target,
1261 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1262 {
1263 if (!target_was_examined(target)) {
1264 LOG_ERROR("Target not examined yet");
1265 return ERROR_FAIL;
1266 }
1267 if (!target->type->write_memory) {
1268 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1269 return ERROR_FAIL;
1270 }
1271 return target->type->write_memory(target, address, size, count, buffer);
1272 }
1273
1274 int target_write_phys_memory(struct target *target,
1275 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1276 {
1277 if (!target_was_examined(target)) {
1278 LOG_ERROR("Target not examined yet");
1279 return ERROR_FAIL;
1280 }
1281 if (!target->type->write_phys_memory) {
1282 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1283 return ERROR_FAIL;
1284 }
1285 return target->type->write_phys_memory(target, address, size, count, buffer);
1286 }
1287
1288 int target_add_breakpoint(struct target *target,
1289 struct breakpoint *breakpoint)
1290 {
1291 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1292 LOG_TARGET_ERROR(target, "not halted (add breakpoint)");
1293 return ERROR_TARGET_NOT_HALTED;
1294 }
1295 return target->type->add_breakpoint(target, breakpoint);
1296 }
1297
1298 int target_add_context_breakpoint(struct target *target,
1299 struct breakpoint *breakpoint)
1300 {
1301 if (target->state != TARGET_HALTED) {
1302 LOG_TARGET_ERROR(target, "not halted (add context breakpoint)");
1303 return ERROR_TARGET_NOT_HALTED;
1304 }
1305 return target->type->add_context_breakpoint(target, breakpoint);
1306 }
1307
1308 int target_add_hybrid_breakpoint(struct target *target,
1309 struct breakpoint *breakpoint)
1310 {
1311 if (target->state != TARGET_HALTED) {
1312 LOG_TARGET_ERROR(target, "not halted (add hybrid breakpoint)");
1313 return ERROR_TARGET_NOT_HALTED;
1314 }
1315 return target->type->add_hybrid_breakpoint(target, breakpoint);
1316 }
1317
1318 int target_remove_breakpoint(struct target *target,
1319 struct breakpoint *breakpoint)
1320 {
1321 return target->type->remove_breakpoint(target, breakpoint);
1322 }
1323
1324 int target_add_watchpoint(struct target *target,
1325 struct watchpoint *watchpoint)
1326 {
1327 if (target->state != TARGET_HALTED) {
1328 LOG_TARGET_ERROR(target, "not halted (add watchpoint)");
1329 return ERROR_TARGET_NOT_HALTED;
1330 }
1331 return target->type->add_watchpoint(target, watchpoint);
1332 }
1333 int target_remove_watchpoint(struct target *target,
1334 struct watchpoint *watchpoint)
1335 {
1336 return target->type->remove_watchpoint(target, watchpoint);
1337 }
1338 int target_hit_watchpoint(struct target *target,
1339 struct watchpoint **hit_watchpoint)
1340 {
1341 if (target->state != TARGET_HALTED) {
1342 LOG_TARGET_ERROR(target, "not halted (hit watchpoint)");
1343 return ERROR_TARGET_NOT_HALTED;
1344 }
1345
1346 if (!target->type->hit_watchpoint) {
1347 /* For backward compatible, if hit_watchpoint is not implemented,
1348 * return ERROR_FAIL such that gdb_server will not take the nonsense
1349 * information. */
1350 return ERROR_FAIL;
1351 }
1352
1353 return target->type->hit_watchpoint(target, hit_watchpoint);
1354 }
1355
1356 const char *target_get_gdb_arch(struct target *target)
1357 {
1358 if (!target->type->get_gdb_arch)
1359 return NULL;
1360 return target->type->get_gdb_arch(target);
1361 }
1362
1363 int target_get_gdb_reg_list(struct target *target,
1364 struct reg **reg_list[], int *reg_list_size,
1365 enum target_register_class reg_class)
1366 {
1367 int result = ERROR_FAIL;
1368
1369 if (!target_was_examined(target)) {
1370 LOG_ERROR("Target not examined yet");
1371 goto done;
1372 }
1373
1374 result = target->type->get_gdb_reg_list(target, reg_list,
1375 reg_list_size, reg_class);
1376
1377 done:
1378 if (result != ERROR_OK) {
1379 *reg_list = NULL;
1380 *reg_list_size = 0;
1381 }
1382 return result;
1383 }
1384
1385 int target_get_gdb_reg_list_noread(struct target *target,
1386 struct reg **reg_list[], int *reg_list_size,
1387 enum target_register_class reg_class)
1388 {
1389 if (target->type->get_gdb_reg_list_noread &&
1390 target->type->get_gdb_reg_list_noread(target, reg_list,
1391 reg_list_size, reg_class) == ERROR_OK)
1392 return ERROR_OK;
1393 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1394 }
1395
1396 bool target_supports_gdb_connection(struct target *target)
1397 {
1398 /*
1399 * exclude all the targets that don't provide get_gdb_reg_list
1400 * or that have explicit gdb_max_connection == 0
1401 */
1402 return !!target->type->get_gdb_reg_list && !!target->gdb_max_connections;
1403 }
1404
1405 int target_step(struct target *target,
1406 int current, target_addr_t address, int handle_breakpoints)
1407 {
1408 int retval;
1409
1410 target_call_event_callbacks(target, TARGET_EVENT_STEP_START);
1411
1412 retval = target->type->step(target, current, address, handle_breakpoints);
1413 if (retval != ERROR_OK)
1414 return retval;
1415
1416 target_call_event_callbacks(target, TARGET_EVENT_STEP_END);
1417
1418 return retval;
1419 }
1420
1421 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1422 {
1423 if (target->state != TARGET_HALTED) {
1424 LOG_TARGET_ERROR(target, "not halted (gdb fileio)");
1425 return ERROR_TARGET_NOT_HALTED;
1426 }
1427 return target->type->get_gdb_fileio_info(target, fileio_info);
1428 }
1429
1430 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1431 {
1432 if (target->state != TARGET_HALTED) {
1433 LOG_TARGET_ERROR(target, "not halted (gdb fileio end)");
1434 return ERROR_TARGET_NOT_HALTED;
1435 }
1436 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1437 }
1438
1439 target_addr_t target_address_max(struct target *target)
1440 {
1441 unsigned bits = target_address_bits(target);
1442 if (sizeof(target_addr_t) * 8 == bits)
1443 return (target_addr_t) -1;
1444 else
1445 return (((target_addr_t) 1) << bits) - 1;
1446 }
1447
1448 unsigned target_address_bits(struct target *target)
1449 {
1450 if (target->type->address_bits)
1451 return target->type->address_bits(target);
1452 return 32;
1453 }
1454
1455 unsigned int target_data_bits(struct target *target)
1456 {
1457 if (target->type->data_bits)
1458 return target->type->data_bits(target);
1459 return 32;
1460 }
1461
1462 static int target_profiling(struct target *target, uint32_t *samples,
1463 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1464 {
1465 return target->type->profiling(target, samples, max_num_samples,
1466 num_samples, seconds);
1467 }
1468
1469 static int handle_target(void *priv);
1470
1471 static int target_init_one(struct command_context *cmd_ctx,
1472 struct target *target)
1473 {
1474 target_reset_examined(target);
1475
1476 struct target_type *type = target->type;
1477 if (!type->examine)
1478 type->examine = default_examine;
1479
1480 if (!type->check_reset)
1481 type->check_reset = default_check_reset;
1482
1483 assert(type->init_target);
1484
1485 int retval = type->init_target(cmd_ctx, target);
1486 if (retval != ERROR_OK) {
1487 LOG_ERROR("target '%s' init failed", target_name(target));
1488 return retval;
1489 }
1490
1491 /* Sanity-check MMU support ... stub in what we must, to help
1492 * implement it in stages, but warn if we need to do so.
1493 */
1494 if (type->mmu) {
1495 if (!type->virt2phys) {
1496 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1497 type->virt2phys = identity_virt2phys;
1498 }
1499 } else {
1500 /* Make sure no-MMU targets all behave the same: make no
1501 * distinction between physical and virtual addresses, and
1502 * ensure that virt2phys() is always an identity mapping.
1503 */
1504 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1505 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1506
1507 type->mmu = no_mmu;
1508 type->write_phys_memory = type->write_memory;
1509 type->read_phys_memory = type->read_memory;
1510 type->virt2phys = identity_virt2phys;
1511 }
1512
1513 if (!target->type->read_buffer)
1514 target->type->read_buffer = target_read_buffer_default;
1515
1516 if (!target->type->write_buffer)
1517 target->type->write_buffer = target_write_buffer_default;
1518
1519 if (!target->type->get_gdb_fileio_info)
1520 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1521
1522 if (!target->type->gdb_fileio_end)
1523 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1524
1525 if (!target->type->profiling)
1526 target->type->profiling = target_profiling_default;
1527
1528 return ERROR_OK;
1529 }
1530
1531 static int target_init(struct command_context *cmd_ctx)
1532 {
1533 struct target *target;
1534 int retval;
1535
1536 for (target = all_targets; target; target = target->next) {
1537 retval = target_init_one(cmd_ctx, target);
1538 if (retval != ERROR_OK)
1539 return retval;
1540 }
1541
1542 if (!all_targets)
1543 return ERROR_OK;
1544
1545 retval = target_register_user_commands(cmd_ctx);
1546 if (retval != ERROR_OK)
1547 return retval;
1548
1549 retval = target_register_timer_callback(&handle_target,
1550 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1551 if (retval != ERROR_OK)
1552 return retval;
1553
1554 return ERROR_OK;
1555 }
1556
1557 COMMAND_HANDLER(handle_target_init_command)
1558 {
1559 int retval;
1560
1561 if (CMD_ARGC != 0)
1562 return ERROR_COMMAND_SYNTAX_ERROR;
1563
1564 static bool target_initialized;
1565 if (target_initialized) {
1566 LOG_INFO("'target init' has already been called");
1567 return ERROR_OK;
1568 }
1569 target_initialized = true;
1570
1571 retval = command_run_line(CMD_CTX, "init_targets");
1572 if (retval != ERROR_OK)
1573 return retval;
1574
1575 retval = command_run_line(CMD_CTX, "init_target_events");
1576 if (retval != ERROR_OK)
1577 return retval;
1578
1579 retval = command_run_line(CMD_CTX, "init_board");
1580 if (retval != ERROR_OK)
1581 return retval;
1582
1583 LOG_DEBUG("Initializing targets...");
1584 return target_init(CMD_CTX);
1585 }
1586
1587 int target_register_event_callback(int (*callback)(struct target *target,
1588 enum target_event event, void *priv), void *priv)
1589 {
1590 struct target_event_callback **callbacks_p = &target_event_callbacks;
1591
1592 if (!callback)
1593 return ERROR_COMMAND_SYNTAX_ERROR;
1594
1595 if (*callbacks_p) {
1596 while ((*callbacks_p)->next)
1597 callbacks_p = &((*callbacks_p)->next);
1598 callbacks_p = &((*callbacks_p)->next);
1599 }
1600
1601 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1602 (*callbacks_p)->callback = callback;
1603 (*callbacks_p)->priv = priv;
1604 (*callbacks_p)->next = NULL;
1605
1606 return ERROR_OK;
1607 }
1608
1609 int target_register_reset_callback(int (*callback)(struct target *target,
1610 enum target_reset_mode reset_mode, void *priv), void *priv)
1611 {
1612 struct target_reset_callback *entry;
1613
1614 if (!callback)
1615 return ERROR_COMMAND_SYNTAX_ERROR;
1616
1617 entry = malloc(sizeof(struct target_reset_callback));
1618 if (!entry) {
1619 LOG_ERROR("error allocating buffer for reset callback entry");
1620 return ERROR_COMMAND_SYNTAX_ERROR;
1621 }
1622
1623 entry->callback = callback;
1624 entry->priv = priv;
1625 list_add(&entry->list, &target_reset_callback_list);
1626
1627
1628 return ERROR_OK;
1629 }
1630
1631 int target_register_trace_callback(int (*callback)(struct target *target,
1632 size_t len, uint8_t *data, void *priv), void *priv)
1633 {
1634 struct target_trace_callback *entry;
1635
1636 if (!callback)
1637 return ERROR_COMMAND_SYNTAX_ERROR;
1638
1639 entry = malloc(sizeof(struct target_trace_callback));
1640 if (!entry) {
1641 LOG_ERROR("error allocating buffer for trace callback entry");
1642 return ERROR_COMMAND_SYNTAX_ERROR;
1643 }
1644
1645 entry->callback = callback;
1646 entry->priv = priv;
1647 list_add(&entry->list, &target_trace_callback_list);
1648
1649
1650 return ERROR_OK;
1651 }
1652
1653 int target_register_timer_callback(int (*callback)(void *priv),
1654 unsigned int time_ms, enum target_timer_type type, void *priv)
1655 {
1656 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1657
1658 if (!callback)
1659 return ERROR_COMMAND_SYNTAX_ERROR;
1660
1661 if (*callbacks_p) {
1662 while ((*callbacks_p)->next)
1663 callbacks_p = &((*callbacks_p)->next);
1664 callbacks_p = &((*callbacks_p)->next);
1665 }
1666
1667 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1668 (*callbacks_p)->callback = callback;
1669 (*callbacks_p)->type = type;
1670 (*callbacks_p)->time_ms = time_ms;
1671 (*callbacks_p)->removed = false;
1672
1673 (*callbacks_p)->when = timeval_ms() + time_ms;
1674 target_timer_next_event_value = MIN(target_timer_next_event_value, (*callbacks_p)->when);
1675
1676 (*callbacks_p)->priv = priv;
1677 (*callbacks_p)->next = NULL;
1678
1679 return ERROR_OK;
1680 }
1681
1682 int target_unregister_event_callback(int (*callback)(struct target *target,
1683 enum target_event event, void *priv), void *priv)
1684 {
1685 struct target_event_callback **p = &target_event_callbacks;
1686 struct target_event_callback *c = target_event_callbacks;
1687
1688 if (!callback)
1689 return ERROR_COMMAND_SYNTAX_ERROR;
1690
1691 while (c) {
1692 struct target_event_callback *next = c->next;
1693 if ((c->callback == callback) && (c->priv == priv)) {
1694 *p = next;
1695 free(c);
1696 return ERROR_OK;
1697 } else
1698 p = &(c->next);
1699 c = next;
1700 }
1701
1702 return ERROR_OK;
1703 }
1704
1705 int target_unregister_reset_callback(int (*callback)(struct target *target,
1706 enum target_reset_mode reset_mode, void *priv), void *priv)
1707 {
1708 struct target_reset_callback *entry;
1709
1710 if (!callback)
1711 return ERROR_COMMAND_SYNTAX_ERROR;
1712
1713 list_for_each_entry(entry, &target_reset_callback_list, list) {
1714 if (entry->callback == callback && entry->priv == priv) {
1715 list_del(&entry->list);
1716 free(entry);
1717 break;
1718 }
1719 }
1720
1721 return ERROR_OK;
1722 }
1723
1724 int target_unregister_trace_callback(int (*callback)(struct target *target,
1725 size_t len, uint8_t *data, void *priv), void *priv)
1726 {
1727 struct target_trace_callback *entry;
1728
1729 if (!callback)
1730 return ERROR_COMMAND_SYNTAX_ERROR;
1731
1732 list_for_each_entry(entry, &target_trace_callback_list, list) {
1733 if (entry->callback == callback && entry->priv == priv) {
1734 list_del(&entry->list);
1735 free(entry);
1736 break;
1737 }
1738 }
1739
1740 return ERROR_OK;
1741 }
1742
1743 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1744 {
1745 if (!callback)
1746 return ERROR_COMMAND_SYNTAX_ERROR;
1747
1748 for (struct target_timer_callback *c = target_timer_callbacks;
1749 c; c = c->next) {
1750 if ((c->callback == callback) && (c->priv == priv)) {
1751 c->removed = true;
1752 return ERROR_OK;
1753 }
1754 }
1755
1756 return ERROR_FAIL;
1757 }
1758
1759 int target_call_event_callbacks(struct target *target, enum target_event event)
1760 {
1761 struct target_event_callback *callback = target_event_callbacks;
1762 struct target_event_callback *next_callback;
1763
1764 if (event == TARGET_EVENT_HALTED) {
1765 /* execute early halted first */
1766 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1767 }
1768
1769 LOG_DEBUG("target event %i (%s) for core %s", event,
1770 target_event_name(event),
1771 target_name(target));
1772
1773 target_handle_event(target, event);
1774
1775 while (callback) {
1776 next_callback = callback->next;
1777 callback->callback(target, event, callback->priv);
1778 callback = next_callback;
1779 }
1780
1781 return ERROR_OK;
1782 }
1783
1784 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1785 {
1786 struct target_reset_callback *callback;
1787
1788 LOG_DEBUG("target reset %i (%s)", reset_mode,
1789 nvp_value2name(nvp_reset_modes, reset_mode)->name);
1790
1791 list_for_each_entry(callback, &target_reset_callback_list, list)
1792 callback->callback(target, reset_mode, callback->priv);
1793
1794 return ERROR_OK;
1795 }
1796
1797 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1798 {
1799 struct target_trace_callback *callback;
1800
1801 list_for_each_entry(callback, &target_trace_callback_list, list)
1802 callback->callback(target, len, data, callback->priv);
1803
1804 return ERROR_OK;
1805 }
1806
1807 static int target_timer_callback_periodic_restart(
1808 struct target_timer_callback *cb, int64_t *now)
1809 {
1810 cb->when = *now + cb->time_ms;
1811 return ERROR_OK;
1812 }
1813
1814 static int target_call_timer_callback(struct target_timer_callback *cb,
1815 int64_t *now)
1816 {
1817 cb->callback(cb->priv);
1818
1819 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1820 return target_timer_callback_periodic_restart(cb, now);
1821
1822 return target_unregister_timer_callback(cb->callback, cb->priv);
1823 }
1824
1825 static int target_call_timer_callbacks_check_time(int checktime)
1826 {
1827 static bool callback_processing;
1828
1829 /* Do not allow nesting */
1830 if (callback_processing)
1831 return ERROR_OK;
1832
1833 callback_processing = true;
1834
1835 keep_alive();
1836
1837 int64_t now = timeval_ms();
1838
1839 /* Initialize to a default value that's a ways into the future.
1840 * The loop below will make it closer to now if there are
1841 * callbacks that want to be called sooner. */
1842 target_timer_next_event_value = now + 1000;
1843
1844 /* Store an address of the place containing a pointer to the
1845 * next item; initially, that's a standalone "root of the
1846 * list" variable. */
1847 struct target_timer_callback **callback = &target_timer_callbacks;
1848 while (callback && *callback) {
1849 if ((*callback)->removed) {
1850 struct target_timer_callback *p = *callback;
1851 *callback = (*callback)->next;
1852 free(p);
1853 continue;
1854 }
1855
1856 bool call_it = (*callback)->callback &&
1857 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1858 now >= (*callback)->when);
1859
1860 if (call_it)
1861 target_call_timer_callback(*callback, &now);
1862
1863 if (!(*callback)->removed && (*callback)->when < target_timer_next_event_value)
1864 target_timer_next_event_value = (*callback)->when;
1865
1866 callback = &(*callback)->next;
1867 }
1868
1869 callback_processing = false;
1870 return ERROR_OK;
1871 }
1872
1873 int target_call_timer_callbacks(void)
1874 {
1875 return target_call_timer_callbacks_check_time(1);
1876 }
1877
1878 /* invoke periodic callbacks immediately */
1879 int target_call_timer_callbacks_now(void)
1880 {
1881 return target_call_timer_callbacks_check_time(0);
1882 }
1883
1884 int64_t target_timer_next_event(void)
1885 {
1886 return target_timer_next_event_value;
1887 }
1888
1889 /* Prints the working area layout for debug purposes */
1890 static void print_wa_layout(struct target *target)
1891 {
1892 struct working_area *c = target->working_areas;
1893
1894 while (c) {
1895 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1896 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1897 c->address, c->address + c->size - 1, c->size);
1898 c = c->next;
1899 }
1900 }
1901
1902 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1903 static void target_split_working_area(struct working_area *area, uint32_t size)
1904 {
1905 assert(area->free); /* Shouldn't split an allocated area */
1906 assert(size <= area->size); /* Caller should guarantee this */
1907
1908 /* Split only if not already the right size */
1909 if (size < area->size) {
1910 struct working_area *new_wa = malloc(sizeof(*new_wa));
1911
1912 if (!new_wa)
1913 return;
1914
1915 new_wa->next = area->next;
1916 new_wa->size = area->size - size;
1917 new_wa->address = area->address + size;
1918 new_wa->backup = NULL;
1919 new_wa->user = NULL;
1920 new_wa->free = true;
1921
1922 area->next = new_wa;
1923 area->size = size;
1924
1925 /* If backup memory was allocated to this area, it has the wrong size
1926 * now so free it and it will be reallocated if/when needed */
1927 free(area->backup);
1928 area->backup = NULL;
1929 }
1930 }
1931
1932 /* Merge all adjacent free areas into one */
1933 static void target_merge_working_areas(struct target *target)
1934 {
1935 struct working_area *c = target->working_areas;
1936
1937 while (c && c->next) {
1938 assert(c->next->address == c->address + c->size); /* This is an invariant */
1939
1940 /* Find two adjacent free areas */
1941 if (c->free && c->next->free) {
1942 /* Merge the last into the first */
1943 c->size += c->next->size;
1944
1945 /* Remove the last */
1946 struct working_area *to_be_freed = c->next;
1947 c->next = c->next->next;
1948 free(to_be_freed->backup);
1949 free(to_be_freed);
1950
1951 /* If backup memory was allocated to the remaining area, it's has
1952 * the wrong size now */
1953 free(c->backup);
1954 c->backup = NULL;
1955 } else {
1956 c = c->next;
1957 }
1958 }
1959 }
1960
1961 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1962 {
1963 /* Reevaluate working area address based on MMU state*/
1964 if (!target->working_areas) {
1965 int retval;
1966 int enabled;
1967
1968 retval = target->type->mmu(target, &enabled);
1969 if (retval != ERROR_OK)
1970 return retval;
1971
1972 if (!enabled) {
1973 if (target->working_area_phys_spec) {
1974 LOG_DEBUG("MMU disabled, using physical "
1975 "address for working memory " TARGET_ADDR_FMT,
1976 target->working_area_phys);
1977 target->working_area = target->working_area_phys;
1978 } else {
1979 LOG_ERROR("No working memory available. "
1980 "Specify -work-area-phys to target.");
1981 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1982 }
1983 } else {
1984 if (target->working_area_virt_spec) {
1985 LOG_DEBUG("MMU enabled, using virtual "
1986 "address for working memory " TARGET_ADDR_FMT,
1987 target->working_area_virt);
1988 target->working_area = target->working_area_virt;
1989 } else {
1990 LOG_ERROR("No working memory available. "
1991 "Specify -work-area-virt to target.");
1992 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1993 }
1994 }
1995
1996 /* Set up initial working area on first call */
1997 struct working_area *new_wa = malloc(sizeof(*new_wa));
1998 if (new_wa) {
1999 new_wa->next = NULL;
2000 new_wa->size = ALIGN_DOWN(target->working_area_size, 4); /* 4-byte align */
2001 new_wa->address = target->working_area;
2002 new_wa->backup = NULL;
2003 new_wa->user = NULL;
2004 new_wa->free = true;
2005 }
2006
2007 target->working_areas = new_wa;
2008 }
2009
2010 /* only allocate multiples of 4 byte */
2011 size = ALIGN_UP(size, 4);
2012
2013 struct working_area *c = target->working_areas;
2014
2015 /* Find the first large enough working area */
2016 while (c) {
2017 if (c->free && c->size >= size)
2018 break;
2019 c = c->next;
2020 }
2021
2022 if (!c)
2023 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2024
2025 /* Split the working area into the requested size */
2026 target_split_working_area(c, size);
2027
2028 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
2029 size, c->address);
2030
2031 if (target->backup_working_area) {
2032 if (!c->backup) {
2033 c->backup = malloc(c->size);
2034 if (!c->backup)
2035 return ERROR_FAIL;
2036 }
2037
2038 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
2039 if (retval != ERROR_OK)
2040 return retval;
2041 }
2042
2043 /* mark as used, and return the new (reused) area */
2044 c->free = false;
2045 *area = c;
2046
2047 /* user pointer */
2048 c->user = area;
2049
2050 print_wa_layout(target);
2051
2052 return ERROR_OK;
2053 }
2054
2055 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
2056 {
2057 int retval;
2058
2059 retval = target_alloc_working_area_try(target, size, area);
2060 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
2061 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
2062 return retval;
2063
2064 }
2065
2066 static int target_restore_working_area(struct target *target, struct working_area *area)
2067 {
2068 int retval = ERROR_OK;
2069
2070 if (target->backup_working_area && area->backup) {
2071 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
2072 if (retval != ERROR_OK)
2073 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2074 area->size, area->address);
2075 }
2076
2077 return retval;
2078 }
2079
2080 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
2081 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
2082 {
2083 if (!area || area->free)
2084 return ERROR_OK;
2085
2086 int retval = ERROR_OK;
2087 if (restore) {
2088 retval = target_restore_working_area(target, area);
2089 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
2090 if (retval != ERROR_OK)
2091 return retval;
2092 }
2093
2094 area->free = true;
2095
2096 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
2097 area->size, area->address);
2098
2099 /* mark user pointer invalid */
2100 /* TODO: Is this really safe? It points to some previous caller's memory.
2101 * How could we know that the area pointer is still in that place and not
2102 * some other vital data? What's the purpose of this, anyway? */
2103 *area->user = NULL;
2104 area->user = NULL;
2105
2106 target_merge_working_areas(target);
2107
2108 print_wa_layout(target);
2109
2110 return retval;
2111 }
2112
2113 int target_free_working_area(struct target *target, struct working_area *area)
2114 {
2115 return target_free_working_area_restore(target, area, 1);
2116 }
2117
2118 /* free resources and restore memory, if restoring memory fails,
2119 * free up resources anyway
2120 */
2121 static void target_free_all_working_areas_restore(struct target *target, int restore)
2122 {
2123 struct working_area *c = target->working_areas;
2124
2125 LOG_DEBUG("freeing all working areas");
2126
2127 /* Loop through all areas, restoring the allocated ones and marking them as free */
2128 while (c) {
2129 if (!c->free) {
2130 if (restore)
2131 target_restore_working_area(target, c);
2132 c->free = true;
2133 *c->user = NULL; /* Same as above */
2134 c->user = NULL;
2135 }
2136 c = c->next;
2137 }
2138
2139 /* Run a merge pass to combine all areas into one */
2140 target_merge_working_areas(target);
2141
2142 print_wa_layout(target);
2143 }
2144
2145 void target_free_all_working_areas(struct target *target)
2146 {
2147 target_free_all_working_areas_restore(target, 1);
2148
2149 /* Now we have none or only one working area marked as free */
2150 if (target->working_areas) {
2151 /* Free the last one to allow on-the-fly moving and resizing */
2152 free(target->working_areas->backup);
2153 free(target->working_areas);
2154 target->working_areas = NULL;
2155 }
2156 }
2157
2158 /* Find the largest number of bytes that can be allocated */
2159 uint32_t target_get_working_area_avail(struct target *target)
2160 {
2161 struct working_area *c = target->working_areas;
2162 uint32_t max_size = 0;
2163
2164 if (!c)
2165 return ALIGN_DOWN(target->working_area_size, 4);
2166
2167 while (c) {
2168 if (c->free && max_size < c->size)
2169 max_size = c->size;
2170
2171 c = c->next;
2172 }
2173
2174 return max_size;
2175 }
2176
2177 static void target_destroy(struct target *target)
2178 {
2179 breakpoint_remove_all(target);
2180 watchpoint_remove_all(target);
2181
2182 if (target->type->deinit_target)
2183 target->type->deinit_target(target);
2184
2185 if (target->semihosting)
2186 free(target->semihosting->basedir);
2187 free(target->semihosting);
2188
2189 jtag_unregister_event_callback(jtag_enable_callback, target);
2190
2191 struct target_event_action *teap = target->event_action;
2192 while (teap) {
2193 struct target_event_action *next = teap->next;
2194 Jim_DecrRefCount(teap->interp, teap->body);
2195 free(teap);
2196 teap = next;
2197 }
2198
2199 target_free_all_working_areas(target);
2200
2201 /* release the targets SMP list */
2202 if (target->smp) {
2203 struct target_list *head, *tmp;
2204
2205 list_for_each_entry_safe(head, tmp, target->smp_targets, lh) {
2206 list_del(&head->lh);
2207 head->target->smp = 0;
2208 free(head);
2209 }
2210 if (target->smp_targets != &empty_smp_targets)
2211 free(target->smp_targets);
2212 target->smp = 0;
2213 }
2214
2215 rtos_destroy(target);
2216
2217 free(target->gdb_port_override);
2218 free(target->type);
2219 free(target->trace_info);
2220 free(target->fileio_info);
2221 free(target->cmd_name);
2222 free(target);
2223 }
2224
2225 void target_quit(void)
2226 {
2227 struct target_event_callback *pe = target_event_callbacks;
2228 while (pe) {
2229 struct target_event_callback *t = pe->next;
2230 free(pe);
2231 pe = t;
2232 }
2233 target_event_callbacks = NULL;
2234
2235 struct target_timer_callback *pt = target_timer_callbacks;
2236 while (pt) {
2237 struct target_timer_callback *t = pt->next;
2238 free(pt);
2239 pt = t;
2240 }
2241 target_timer_callbacks = NULL;
2242
2243 for (struct target *target = all_targets; target;) {
2244 struct target *tmp;
2245
2246 tmp = target->next;
2247 target_destroy(target);
2248 target = tmp;
2249 }
2250
2251 all_targets = NULL;
2252 }
2253
2254 int target_arch_state(struct target *target)
2255 {
2256 int retval;
2257 if (!target) {
2258 LOG_WARNING("No target has been configured");
2259 return ERROR_OK;
2260 }
2261
2262 if (target->state != TARGET_HALTED)
2263 return ERROR_OK;
2264
2265 retval = target->type->arch_state(target);
2266 return retval;
2267 }
2268
2269 static int target_get_gdb_fileio_info_default(struct target *target,
2270 struct gdb_fileio_info *fileio_info)
2271 {
2272 /* If target does not support semi-hosting function, target
2273 has no need to provide .get_gdb_fileio_info callback.
2274 It just return ERROR_FAIL and gdb_server will return "Txx"
2275 as target halted every time. */
2276 return ERROR_FAIL;
2277 }
2278
2279 static int target_gdb_fileio_end_default(struct target *target,
2280 int retcode, int fileio_errno, bool ctrl_c)
2281 {
2282 return ERROR_OK;
2283 }
2284
2285 int target_profiling_default(struct target *target, uint32_t *samples,
2286 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2287 {
2288 struct timeval timeout, now;
2289
2290 gettimeofday(&timeout, NULL);
2291 timeval_add_time(&timeout, seconds, 0);
2292
2293 LOG_INFO("Starting profiling. Halting and resuming the"
2294 " target as often as we can...");
2295
2296 uint32_t sample_count = 0;
2297 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2298 struct reg *reg = register_get_by_name(target->reg_cache, "pc", true);
2299
2300 int retval = ERROR_OK;
2301 for (;;) {
2302 target_poll(target);
2303 if (target->state == TARGET_HALTED) {
2304 uint32_t t = buf_get_u32(reg->value, 0, 32);
2305 samples[sample_count++] = t;
2306 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2307 retval = target_resume(target, 1, 0, 0, 0);
2308 target_poll(target);
2309 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2310 } else if (target->state == TARGET_RUNNING) {
2311 /* We want to quickly sample the PC. */
2312 retval = target_halt(target);
2313 } else {
2314 LOG_INFO("Target not halted or running");
2315 retval = ERROR_OK;
2316 break;
2317 }
2318
2319 if (retval != ERROR_OK)
2320 break;
2321
2322 gettimeofday(&now, NULL);
2323 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2324 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2325 break;
2326 }
2327 }
2328
2329 *num_samples = sample_count;
2330 return retval;
2331 }
2332
2333 /* Single aligned words are guaranteed to use 16 or 32 bit access
2334 * mode respectively, otherwise data is handled as quickly as
2335 * possible
2336 */
2337 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2338 {
2339 LOG_DEBUG("writing buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2340 size, address);
2341
2342 if (!target_was_examined(target)) {
2343 LOG_ERROR("Target not examined yet");
2344 return ERROR_FAIL;
2345 }
2346
2347 if (size == 0)
2348 return ERROR_OK;
2349
2350 if ((address + size - 1) < address) {
2351 /* GDB can request this when e.g. PC is 0xfffffffc */
2352 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2353 address,
2354 size);
2355 return ERROR_FAIL;
2356 }
2357
2358 return target->type->write_buffer(target, address, size, buffer);
2359 }
2360
2361 static int target_write_buffer_default(struct target *target,
2362 target_addr_t address, uint32_t count, const uint8_t *buffer)
2363 {
2364 uint32_t size;
2365 unsigned int data_bytes = target_data_bits(target) / 8;
2366
2367 /* Align up to maximum bytes. The loop condition makes sure the next pass
2368 * will have something to do with the size we leave to it. */
2369 for (size = 1;
2370 size < data_bytes && count >= size * 2 + (address & size);
2371 size *= 2) {
2372 if (address & size) {
2373 int retval = target_write_memory(target, address, size, 1, buffer);
2374 if (retval != ERROR_OK)
2375 return retval;
2376 address += size;
2377 count -= size;
2378 buffer += size;
2379 }
2380 }
2381
2382 /* Write the data with as large access size as possible. */
2383 for (; size > 0; size /= 2) {
2384 uint32_t aligned = count - count % size;
2385 if (aligned > 0) {
2386 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2387 if (retval != ERROR_OK)
2388 return retval;
2389 address += aligned;
2390 count -= aligned;
2391 buffer += aligned;
2392 }
2393 }
2394
2395 return ERROR_OK;
2396 }
2397
2398 /* Single aligned words are guaranteed to use 16 or 32 bit access
2399 * mode respectively, otherwise data is handled as quickly as
2400 * possible
2401 */
2402 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2403 {
2404 LOG_DEBUG("reading buffer of %" PRIu32 " byte at " TARGET_ADDR_FMT,
2405 size, address);
2406
2407 if (!target_was_examined(target)) {
2408 LOG_ERROR("Target not examined yet");
2409 return ERROR_FAIL;
2410 }
2411
2412 if (size == 0)
2413 return ERROR_OK;
2414
2415 if ((address + size - 1) < address) {
2416 /* GDB can request this when e.g. PC is 0xfffffffc */
2417 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2418 address,
2419 size);
2420 return ERROR_FAIL;
2421 }
2422
2423 return target->type->read_buffer(target, address, size, buffer);
2424 }
2425
2426 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2427 {
2428 uint32_t size;
2429 unsigned int data_bytes = target_data_bits(target) / 8;
2430
2431 /* Align up to maximum bytes. The loop condition makes sure the next pass
2432 * will have something to do with the size we leave to it. */
2433 for (size = 1;
2434 size < data_bytes && count >= size * 2 + (address & size);
2435 size *= 2) {
2436 if (address & size) {
2437 int retval = target_read_memory(target, address, size, 1, buffer);
2438 if (retval != ERROR_OK)
2439 return retval;
2440 address += size;
2441 count -= size;
2442 buffer += size;
2443 }
2444 }
2445
2446 /* Read the data with as large access size as possible. */
2447 for (; size > 0; size /= 2) {
2448 uint32_t aligned = count - count % size;
2449 if (aligned > 0) {
2450 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2451 if (retval != ERROR_OK)
2452 return retval;
2453 address += aligned;
2454 count -= aligned;
2455 buffer += aligned;
2456 }
2457 }
2458
2459 return ERROR_OK;
2460 }
2461
2462 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t *crc)
2463 {
2464 uint8_t *buffer;
2465 int retval;
2466 uint32_t i;
2467 uint32_t checksum = 0;
2468 if (!target_was_examined(target)) {
2469 LOG_ERROR("Target not examined yet");
2470 return ERROR_FAIL;
2471 }
2472 if (!target->type->checksum_memory) {
2473 LOG_ERROR("Target %s doesn't support checksum_memory", target_name(target));
2474 return ERROR_FAIL;
2475 }
2476
2477 retval = target->type->checksum_memory(target, address, size, &checksum);
2478 if (retval != ERROR_OK) {
2479 buffer = malloc(size);
2480 if (!buffer) {
2481 LOG_ERROR("error allocating buffer for section (%" PRIu32 " bytes)", size);
2482 return ERROR_COMMAND_SYNTAX_ERROR;
2483 }
2484 retval = target_read_buffer(target, address, size, buffer);
2485 if (retval != ERROR_OK) {
2486 free(buffer);
2487 return retval;
2488 }
2489
2490 /* convert to target endianness */
2491 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2492 uint32_t target_data;
2493 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2494 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2495 }
2496
2497 retval = image_calculate_checksum(buffer, size, &checksum);
2498 free(buffer);
2499 }
2500
2501 *crc = checksum;
2502
2503 return retval;
2504 }
2505
2506 int target_blank_check_memory(struct target *target,
2507 struct target_memory_check_block *blocks, int num_blocks,
2508 uint8_t erased_value)
2509 {
2510 if (!target_was_examined(target)) {
2511 LOG_ERROR("Target not examined yet");
2512 return ERROR_FAIL;
2513 }
2514
2515 if (!target->type->blank_check_memory)
2516 return ERROR_NOT_IMPLEMENTED;
2517
2518 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2519 }
2520
2521 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2522 {
2523 uint8_t value_buf[8];
2524 if (!target_was_examined(target)) {
2525 LOG_ERROR("Target not examined yet");
2526 return ERROR_FAIL;
2527 }
2528
2529 int retval = target_read_memory(target, address, 8, 1, value_buf);
2530
2531 if (retval == ERROR_OK) {
2532 *value = target_buffer_get_u64(target, value_buf);
2533 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2534 address,
2535 *value);
2536 } else {
2537 *value = 0x0;
2538 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2539 address);
2540 }
2541
2542 return retval;
2543 }
2544
2545 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2546 {
2547 uint8_t value_buf[4];
2548 if (!target_was_examined(target)) {
2549 LOG_ERROR("Target not examined yet");
2550 return ERROR_FAIL;
2551 }
2552
2553 int retval = target_read_memory(target, address, 4, 1, value_buf);
2554
2555 if (retval == ERROR_OK) {
2556 *value = target_buffer_get_u32(target, value_buf);
2557 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2558 address,
2559 *value);
2560 } else {
2561 *value = 0x0;
2562 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2563 address);
2564 }
2565
2566 return retval;
2567 }
2568
2569 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2570 {
2571 uint8_t value_buf[2];
2572 if (!target_was_examined(target)) {
2573 LOG_ERROR("Target not examined yet");
2574 return ERROR_FAIL;
2575 }
2576
2577 int retval = target_read_memory(target, address, 2, 1, value_buf);
2578
2579 if (retval == ERROR_OK) {
2580 *value = target_buffer_get_u16(target, value_buf);
2581 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2582 address,
2583 *value);
2584 } else {
2585 *value = 0x0;
2586 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2587 address);
2588 }
2589
2590 return retval;
2591 }
2592
2593 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2594 {
2595 if (!target_was_examined(target)) {
2596 LOG_ERROR("Target not examined yet");
2597 return ERROR_FAIL;
2598 }
2599
2600 int retval = target_read_memory(target, address, 1, 1, value);
2601
2602 if (retval == ERROR_OK) {
2603 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2604 address,
2605 *value);
2606 } else {
2607 *value = 0x0;
2608 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2609 address);
2610 }
2611
2612 return retval;
2613 }
2614
2615 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2616 {
2617 int retval;
2618 uint8_t value_buf[8];
2619 if (!target_was_examined(target)) {
2620 LOG_ERROR("Target not examined yet");
2621 return ERROR_FAIL;
2622 }
2623
2624 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2625 address,
2626 value);
2627
2628 target_buffer_set_u64(target, value_buf, value);
2629 retval = target_write_memory(target, address, 8, 1, value_buf);
2630 if (retval != ERROR_OK)
2631 LOG_DEBUG("failed: %i", retval);
2632
2633 return retval;
2634 }
2635
2636 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2637 {
2638 int retval;
2639 uint8_t value_buf[4];
2640 if (!target_was_examined(target)) {
2641 LOG_ERROR("Target not examined yet");
2642 return ERROR_FAIL;
2643 }
2644
2645 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2646 address,
2647 value);
2648
2649 target_buffer_set_u32(target, value_buf, value);
2650 retval = target_write_memory(target, address, 4, 1, value_buf);
2651 if (retval != ERROR_OK)
2652 LOG_DEBUG("failed: %i", retval);
2653
2654 return retval;
2655 }
2656
2657 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2658 {
2659 int retval;
2660 uint8_t value_buf[2];
2661 if (!target_was_examined(target)) {
2662 LOG_ERROR("Target not examined yet");
2663 return ERROR_FAIL;
2664 }
2665
2666 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2667 address,
2668 value);
2669
2670 target_buffer_set_u16(target, value_buf, value);
2671 retval = target_write_memory(target, address, 2, 1, value_buf);
2672 if (retval != ERROR_OK)
2673 LOG_DEBUG("failed: %i", retval);
2674
2675 return retval;
2676 }
2677
2678 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2679 {
2680 int retval;
2681 if (!target_was_examined(target)) {
2682 LOG_ERROR("Target not examined yet");
2683 return ERROR_FAIL;
2684 }
2685
2686 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2687 address, value);
2688
2689 retval = target_write_memory(target, address, 1, 1, &value);
2690 if (retval != ERROR_OK)
2691 LOG_DEBUG("failed: %i", retval);
2692
2693 return retval;
2694 }
2695
2696 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2697 {
2698 int retval;
2699 uint8_t value_buf[8];
2700 if (!target_was_examined(target)) {
2701 LOG_ERROR("Target not examined yet");
2702 return ERROR_FAIL;
2703 }
2704
2705 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2706 address,
2707 value);
2708
2709 target_buffer_set_u64(target, value_buf, value);
2710 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2711 if (retval != ERROR_OK)
2712 LOG_DEBUG("failed: %i", retval);
2713
2714 return retval;
2715 }
2716
2717 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2718 {
2719 int retval;
2720 uint8_t value_buf[4];
2721 if (!target_was_examined(target)) {
2722 LOG_ERROR("Target not examined yet");
2723 return ERROR_FAIL;
2724 }
2725
2726 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2727 address,
2728 value);
2729
2730 target_buffer_set_u32(target, value_buf, value);
2731 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2732 if (retval != ERROR_OK)
2733 LOG_DEBUG("failed: %i", retval);
2734
2735 return retval;
2736 }
2737
2738 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2739 {
2740 int retval;
2741 uint8_t value_buf[2];
2742 if (!target_was_examined(target)) {
2743 LOG_ERROR("Target not examined yet");
2744 return ERROR_FAIL;
2745 }
2746
2747 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2748 address,
2749 value);
2750
2751 target_buffer_set_u16(target, value_buf, value);
2752 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2753 if (retval != ERROR_OK)
2754 LOG_DEBUG("failed: %i", retval);
2755
2756 return retval;
2757 }
2758
2759 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2760 {
2761 int retval;
2762 if (!target_was_examined(target)) {
2763 LOG_ERROR("Target not examined yet");
2764 return ERROR_FAIL;
2765 }
2766
2767 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2768 address, value);
2769
2770 retval = target_write_phys_memory(target, address, 1, 1, &value);
2771 if (retval != ERROR_OK)
2772 LOG_DEBUG("failed: %i", retval);
2773
2774 return retval;
2775 }
2776
2777 static int find_target(struct command_invocation *cmd, const char *name)
2778 {
2779 struct target *target = get_target(name);
2780 if (!target) {
2781 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2782 return ERROR_FAIL;
2783 }
2784 if (!target->tap->enabled) {
2785 command_print(cmd, "Target: TAP %s is disabled, "
2786 "can't be the current target\n",
2787 target->tap->dotted_name);
2788 return ERROR_FAIL;
2789 }
2790
2791 cmd->ctx->current_target = target;
2792 if (cmd->ctx->current_target_override)
2793 cmd->ctx->current_target_override = target;
2794
2795 return ERROR_OK;
2796 }
2797
2798
2799 COMMAND_HANDLER(handle_targets_command)
2800 {
2801 int retval = ERROR_OK;
2802 if (CMD_ARGC == 1) {
2803 retval = find_target(CMD, CMD_ARGV[0]);
2804 if (retval == ERROR_OK) {
2805 /* we're done! */
2806 return retval;
2807 }
2808 }
2809
2810 unsigned int index = 0;
2811 command_print(CMD, " TargetName Type Endian TapName State ");
2812 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2813 for (struct target *target = all_targets; target; target = target->next, ++index) {
2814 const char *state;
2815 char marker = ' ';
2816
2817 if (target->tap->enabled)
2818 state = target_state_name(target);
2819 else
2820 state = "tap-disabled";
2821
2822 if (CMD_CTX->current_target == target)
2823 marker = '*';
2824
2825 /* keep columns lined up to match the headers above */
2826 command_print(CMD,
2827 "%2d%c %-18s %-10s %-6s %-18s %s",
2828 index,
2829 marker,
2830 target_name(target),
2831 target_type_name(target),
2832 jim_nvp_value2name_simple(nvp_target_endian,
2833 target->endianness)->name,
2834 target->tap->dotted_name,
2835 state);
2836 }
2837
2838 return retval;
2839 }
2840
2841 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2842
2843 static int power_dropout;
2844 static int srst_asserted;
2845
2846 static int run_power_restore;
2847 static int run_power_dropout;
2848 static int run_srst_asserted;
2849 static int run_srst_deasserted;
2850
2851 static int sense_handler(void)
2852 {
2853 static int prev_srst_asserted;
2854 static int prev_power_dropout;
2855
2856 int retval = jtag_power_dropout(&power_dropout);
2857 if (retval != ERROR_OK)
2858 return retval;
2859
2860 int power_restored;
2861 power_restored = prev_power_dropout && !power_dropout;
2862 if (power_restored)
2863 run_power_restore = 1;
2864
2865 int64_t current = timeval_ms();
2866 static int64_t last_power;
2867 bool wait_more = last_power + 2000 > current;
2868 if (power_dropout && !wait_more) {
2869 run_power_dropout = 1;
2870 last_power = current;
2871 }
2872
2873 retval = jtag_srst_asserted(&srst_asserted);
2874 if (retval != ERROR_OK)
2875 return retval;
2876
2877 int srst_deasserted;
2878 srst_deasserted = prev_srst_asserted && !srst_asserted;
2879
2880 static int64_t last_srst;
2881 wait_more = last_srst + 2000 > current;
2882 if (srst_deasserted && !wait_more) {
2883 run_srst_deasserted = 1;
2884 last_srst = current;
2885 }
2886
2887 if (!prev_srst_asserted && srst_asserted)
2888 run_srst_asserted = 1;
2889
2890 prev_srst_asserted = srst_asserted;
2891 prev_power_dropout = power_dropout;
2892
2893 if (srst_deasserted || power_restored) {
2894 /* Other than logging the event we can't do anything here.
2895 * Issuing a reset is a particularly bad idea as we might
2896 * be inside a reset already.
2897 */
2898 }
2899
2900 return ERROR_OK;
2901 }
2902
2903 /* process target state changes */
2904 static int handle_target(void *priv)
2905 {
2906 Jim_Interp *interp = (Jim_Interp *)priv;
2907 int retval = ERROR_OK;
2908
2909 if (!is_jtag_poll_safe()) {
2910 /* polling is disabled currently */
2911 return ERROR_OK;
2912 }
2913
2914 /* we do not want to recurse here... */
2915 static int recursive;
2916 if (!recursive) {
2917 recursive = 1;
2918 sense_handler();
2919 /* danger! running these procedures can trigger srst assertions and power dropouts.
2920 * We need to avoid an infinite loop/recursion here and we do that by
2921 * clearing the flags after running these events.
2922 */
2923 int did_something = 0;
2924 if (run_srst_asserted) {
2925 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2926 Jim_Eval(interp, "srst_asserted");
2927 did_something = 1;
2928 }
2929 if (run_srst_deasserted) {
2930 Jim_Eval(interp, "srst_deasserted");
2931 did_something = 1;
2932 }
2933 if (run_power_dropout) {
2934 LOG_INFO("Power dropout detected, running power_dropout proc.");
2935 Jim_Eval(interp, "power_dropout");
2936 did_something = 1;
2937 }
2938 if (run_power_restore) {
2939 Jim_Eval(interp, "power_restore");
2940 did_something = 1;
2941 }
2942
2943 if (did_something) {
2944 /* clear detect flags */
2945 sense_handler();
2946 }
2947
2948 /* clear action flags */
2949
2950 run_srst_asserted = 0;
2951 run_srst_deasserted = 0;
2952 run_power_restore = 0;
2953 run_power_dropout = 0;
2954
2955 recursive = 0;
2956 }
2957
2958 /* Poll targets for state changes unless that's globally disabled.
2959 * Skip targets that are currently disabled.
2960 */
2961 for (struct target *target = all_targets;
2962 is_jtag_poll_safe() && target;
2963 target = target->next) {
2964
2965 if (!target_was_examined(target))
2966 continue;
2967
2968 if (!target->tap->enabled)
2969 continue;
2970
2971 if (target->backoff.times > target->backoff.count) {
2972 /* do not poll this time as we failed previously */
2973 target->backoff.count++;
2974 continue;
2975 }
2976 target->backoff.count = 0;
2977
2978 /* only poll target if we've got power and srst isn't asserted */
2979 if (!power_dropout && !srst_asserted) {
2980 /* polling may fail silently until the target has been examined */
2981 retval = target_poll(target);
2982 if (retval != ERROR_OK) {
2983 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2984 if (target->backoff.times * polling_interval < 5000) {
2985 target->backoff.times *= 2;
2986 target->backoff.times++;
2987 }
2988
2989 /* Tell GDB to halt the debugger. This allows the user to
2990 * run monitor commands to handle the situation.
2991 */
2992 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2993 }
2994 if (target->backoff.times > 0) {
2995 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
2996 target_reset_examined(target);
2997 retval = target_examine_one(target);
2998 /* Target examination could have failed due to unstable connection,
2999 * but we set the examined flag anyway to repoll it later */
3000 if (retval != ERROR_OK) {
3001 target_set_examined(target);
3002 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
3003 target->backoff.times * polling_interval);
3004 return retval;
3005 }
3006 }
3007
3008 /* Since we succeeded, we reset backoff count */
3009 target->backoff.times = 0;
3010 }
3011 }
3012
3013 return retval;
3014 }
3015
3016 COMMAND_HANDLER(handle_reg_command)
3017 {
3018 LOG_DEBUG("-");
3019
3020 struct target *target = get_current_target(CMD_CTX);
3021 if (!target_was_examined(target)) {
3022 LOG_ERROR("Target not examined yet");
3023 return ERROR_TARGET_NOT_EXAMINED;
3024 }
3025 struct reg *reg = NULL;
3026
3027 /* list all available registers for the current target */
3028 if (CMD_ARGC == 0) {
3029 struct reg_cache *cache = target->reg_cache;
3030
3031 unsigned int count = 0;
3032 while (cache) {
3033 unsigned i;
3034
3035 command_print(CMD, "===== %s", cache->name);
3036
3037 for (i = 0, reg = cache->reg_list;
3038 i < cache->num_regs;
3039 i++, reg++, count++) {
3040 if (reg->exist == false || reg->hidden)
3041 continue;
3042 /* only print cached values if they are valid */
3043 if (reg->valid) {
3044 char *value = buf_to_hex_str(reg->value,
3045 reg->size);
3046 command_print(CMD,
3047 "(%i) %s (/%" PRIu32 "): 0x%s%s",
3048 count, reg->name,
3049 reg->size, value,
3050 reg->dirty
3051 ? " (dirty)"
3052 : "");
3053 free(value);
3054 } else {
3055 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
3056 count, reg->name,
3057 reg->size);
3058 }
3059 }
3060 cache = cache->next;
3061 }
3062
3063 return ERROR_OK;
3064 }
3065
3066 /* access a single register by its ordinal number */
3067 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
3068 unsigned num;
3069 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
3070
3071 struct reg_cache *cache = target->reg_cache;
3072 unsigned int count = 0;
3073 while (cache) {
3074 unsigned i;
3075 for (i = 0; i < cache->num_regs; i++) {
3076 if (count++ == num) {
3077 reg = &cache->reg_list[i];
3078 break;
3079 }
3080 }
3081 if (reg)
3082 break;
3083 cache = cache->next;
3084 }
3085
3086 if (!reg) {
3087 command_print(CMD, "%i is out of bounds, the current target "
3088 "has only %i registers (0 - %i)", num, count, count - 1);
3089 return ERROR_FAIL;
3090 }
3091 } else {
3092 /* access a single register by its name */
3093 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], true);
3094
3095 if (!reg)
3096 goto not_found;
3097 }
3098
3099 assert(reg); /* give clang a hint that we *know* reg is != NULL here */
3100
3101 if (!reg->exist)
3102 goto not_found;
3103
3104 /* display a register */
3105 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
3106 && (CMD_ARGV[1][0] <= '9')))) {
3107 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
3108 reg->valid = false;
3109
3110 if (!reg->valid) {
3111 int retval = reg->type->get(reg);
3112 if (retval != ERROR_OK) {
3113 LOG_ERROR("Could not read register '%s'", reg->name);
3114 return retval;
3115 }
3116 }
3117 char *value = buf_to_hex_str(reg->value, reg->size);
3118 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3119 free(value);
3120 return ERROR_OK;
3121 }
3122
3123 /* set register value */
3124 if (CMD_ARGC == 2) {
3125 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
3126 if (!buf)
3127 return ERROR_FAIL;
3128 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
3129
3130 int retval = reg->type->set(reg, buf);
3131 if (retval != ERROR_OK) {
3132 LOG_ERROR("Could not write to register '%s'", reg->name);
3133 } else {
3134 char *value = buf_to_hex_str(reg->value, reg->size);
3135 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
3136 free(value);
3137 }
3138
3139 free(buf);
3140
3141 return retval;
3142 }
3143
3144 return ERROR_COMMAND_SYNTAX_ERROR;
3145
3146 not_found:
3147 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
3148 return ERROR_FAIL;
3149 }
3150
3151 COMMAND_HANDLER(handle_poll_command)
3152 {
3153 int retval = ERROR_OK;
3154 struct target *target = get_current_target(CMD_CTX);
3155
3156 if (CMD_ARGC == 0) {
3157 command_print(CMD, "background polling: %s",
3158 jtag_poll_get_enabled() ? "on" : "off");
3159 command_print(CMD, "TAP: %s (%s)",
3160 target->tap->dotted_name,
3161 target->tap->enabled ? "enabled" : "disabled");
3162 if (!target->tap->enabled)
3163 return ERROR_OK;
3164 retval = target_poll(target);
3165 if (retval != ERROR_OK)
3166 return retval;
3167 retval = target_arch_state(target);
3168 if (retval != ERROR_OK)
3169 return retval;
3170 } else if (CMD_ARGC == 1) {
3171 bool enable;
3172 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
3173 jtag_poll_set_enabled(enable);
3174 } else
3175 return ERROR_COMMAND_SYNTAX_ERROR;
3176
3177 return retval;
3178 }
3179
3180 COMMAND_HANDLER(handle_wait_halt_command)
3181 {
3182 if (CMD_ARGC > 1)
3183 return ERROR_COMMAND_SYNTAX_ERROR;
3184
3185 unsigned ms = DEFAULT_HALT_TIMEOUT;
3186 if (1 == CMD_ARGC) {
3187 int retval = parse_uint(CMD_ARGV[0], &ms);
3188 if (retval != ERROR_OK)
3189 return ERROR_COMMAND_SYNTAX_ERROR;
3190 }
3191
3192 struct target *target = get_current_target(CMD_CTX);
3193 return target_wait_state(target, TARGET_HALTED, ms);
3194 }
3195
3196 /* wait for target state to change. The trick here is to have a low
3197 * latency for short waits and not to suck up all the CPU time
3198 * on longer waits.
3199 *
3200 * After 500ms, keep_alive() is invoked
3201 */
3202 int target_wait_state(struct target *target, enum target_state state, unsigned int ms)
3203 {
3204 int retval;
3205 int64_t then = 0, cur;
3206 bool once = true;
3207
3208 for (;;) {
3209 retval = target_poll(target);
3210 if (retval != ERROR_OK)
3211 return retval;
3212 if (target->state == state)
3213 break;
3214 cur = timeval_ms();
3215 if (once) {
3216 once = false;
3217 then = timeval_ms();
3218 LOG_DEBUG("waiting for target %s...",
3219 nvp_value2name(nvp_target_state, state)->name);
3220 }
3221
3222 if (cur-then > 500)
3223 keep_alive();
3224
3225 if ((cur-then) > ms) {
3226 LOG_ERROR("timed out while waiting for target %s",
3227 nvp_value2name(nvp_target_state, state)->name);
3228 return ERROR_FAIL;
3229 }
3230 }
3231
3232 return ERROR_OK;
3233 }
3234
3235 COMMAND_HANDLER(handle_halt_command)
3236 {
3237 LOG_DEBUG("-");
3238
3239 struct target *target = get_current_target(CMD_CTX);
3240
3241 target->verbose_halt_msg = true;
3242
3243 int retval = target_halt(target);
3244 if (retval != ERROR_OK)
3245 return retval;
3246
3247 if (CMD_ARGC == 1) {
3248 unsigned wait_local;
3249 retval = parse_uint(CMD_ARGV[0], &wait_local);
3250 if (retval != ERROR_OK)
3251 return ERROR_COMMAND_SYNTAX_ERROR;
3252 if (!wait_local)
3253 return ERROR_OK;
3254 }
3255
3256 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3257 }
3258
3259 COMMAND_HANDLER(handle_soft_reset_halt_command)
3260 {
3261 struct target *target = get_current_target(CMD_CTX);
3262
3263 LOG_TARGET_INFO(target, "requesting target halt and executing a soft reset");
3264
3265 target_soft_reset_halt(target);
3266
3267 return ERROR_OK;
3268 }
3269
3270 COMMAND_HANDLER(handle_reset_command)
3271 {
3272 if (CMD_ARGC > 1)
3273 return ERROR_COMMAND_SYNTAX_ERROR;
3274
3275 enum target_reset_mode reset_mode = RESET_RUN;
3276 if (CMD_ARGC == 1) {
3277 const struct nvp *n;
3278 n = nvp_name2value(nvp_reset_modes, CMD_ARGV[0]);
3279 if ((!n->name) || (n->value == RESET_UNKNOWN))
3280 return ERROR_COMMAND_SYNTAX_ERROR;
3281 reset_mode = n->value;
3282 }
3283
3284 /* reset *all* targets */
3285 return target_process_reset(CMD, reset_mode);
3286 }
3287
3288
3289 COMMAND_HANDLER(handle_resume_command)
3290 {
3291 int current = 1;
3292 if (CMD_ARGC > 1)
3293 return ERROR_COMMAND_SYNTAX_ERROR;
3294
3295 struct target *target = get_current_target(CMD_CTX);
3296
3297 /* with no CMD_ARGV, resume from current pc, addr = 0,
3298 * with one arguments, addr = CMD_ARGV[0],
3299 * handle breakpoints, not debugging */
3300 target_addr_t addr = 0;
3301 if (CMD_ARGC == 1) {
3302 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3303 current = 0;
3304 }
3305
3306 return target_resume(target, current, addr, 1, 0);
3307 }
3308
3309 COMMAND_HANDLER(handle_step_command)
3310 {
3311 if (CMD_ARGC > 1)
3312 return ERROR_COMMAND_SYNTAX_ERROR;
3313
3314 LOG_DEBUG("-");
3315
3316 /* with no CMD_ARGV, step from current pc, addr = 0,
3317 * with one argument addr = CMD_ARGV[0],
3318 * handle breakpoints, debugging */
3319 target_addr_t addr = 0;
3320 int current_pc = 1;
3321 if (CMD_ARGC == 1) {
3322 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3323 current_pc = 0;
3324 }
3325
3326 struct target *target = get_current_target(CMD_CTX);
3327
3328 return target_step(target, current_pc, addr, 1);
3329 }
3330
3331 void target_handle_md_output(struct command_invocation *cmd,
3332 struct target *target, target_addr_t address, unsigned size,
3333 unsigned count, const uint8_t *buffer)
3334 {
3335 const unsigned line_bytecnt = 32;
3336 unsigned line_modulo = line_bytecnt / size;
3337
3338 char output[line_bytecnt * 4 + 1];
3339 unsigned output_len = 0;
3340
3341 const char *value_fmt;
3342 switch (size) {
3343 case 8:
3344 value_fmt = "%16.16"PRIx64" ";
3345 break;
3346 case 4:
3347 value_fmt = "%8.8"PRIx64" ";
3348 break;
3349 case 2:
3350 value_fmt = "%4.4"PRIx64" ";
3351 break;
3352 case 1:
3353 value_fmt = "%2.2"PRIx64" ";
3354 break;
3355 default:
3356 /* "can't happen", caller checked */
3357 LOG_ERROR("invalid memory read size: %u", size);
3358 return;
3359 }
3360
3361 for (unsigned i = 0; i < count; i++) {
3362 if (i % line_modulo == 0) {
3363 output_len += snprintf(output + output_len,
3364 sizeof(output) - output_len,
3365 TARGET_ADDR_FMT ": ",
3366 (address + (i * size)));
3367 }
3368
3369 uint64_t value = 0;
3370 const uint8_t *value_ptr = buffer + i * size;
3371 switch (size) {
3372 case 8:
3373 value = target_buffer_get_u64(target, value_ptr);
3374 break;
3375 case 4:
3376 value = target_buffer_get_u32(target, value_ptr);
3377 break;
3378 case 2:
3379 value = target_buffer_get_u16(target, value_ptr);
3380 break;
3381 case 1:
3382 value = *value_ptr;
3383 }
3384 output_len += snprintf(output + output_len,
3385 sizeof(output) - output_len,
3386 value_fmt, value);
3387
3388 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3389 command_print(cmd, "%s", output);
3390 output_len = 0;
3391 }
3392 }
3393 }
3394
3395 COMMAND_HANDLER(handle_md_command)
3396 {
3397 if (CMD_ARGC < 1)
3398 return ERROR_COMMAND_SYNTAX_ERROR;
3399
3400 unsigned size = 0;
3401 switch (CMD_NAME[2]) {
3402 case 'd':
3403 size = 8;
3404 break;
3405 case 'w':
3406 size = 4;
3407 break;
3408 case 'h':
3409 size = 2;
3410 break;
3411 case 'b':
3412 size = 1;
3413 break;
3414 default:
3415 return ERROR_COMMAND_SYNTAX_ERROR;
3416 }
3417
3418 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3419 int (*fn)(struct target *target,
3420 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3421 if (physical) {
3422 CMD_ARGC--;
3423 CMD_ARGV++;
3424 fn = target_read_phys_memory;
3425 } else
3426 fn = target_read_memory;
3427 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3428 return ERROR_COMMAND_SYNTAX_ERROR;
3429
3430 target_addr_t address;
3431 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3432
3433 unsigned count = 1;
3434 if (CMD_ARGC == 2)
3435 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3436
3437 uint8_t *buffer = calloc(count, size);
3438 if (!buffer) {
3439 LOG_ERROR("Failed to allocate md read buffer");
3440 return ERROR_FAIL;
3441 }
3442
3443 struct target *target = get_current_target(CMD_CTX);
3444 int retval = fn(target, address, size, count, buffer);
3445 if (retval == ERROR_OK)
3446 target_handle_md_output(CMD, target, address, size, count, buffer);
3447
3448 free(buffer);
3449
3450 return retval;
3451 }
3452
3453 typedef int (*target_write_fn)(struct target *target,
3454 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3455
3456 static int target_fill_mem(struct target *target,
3457 target_addr_t address,
3458 target_write_fn fn,
3459 unsigned data_size,
3460 /* value */
3461 uint64_t b,
3462 /* count */
3463 unsigned c)
3464 {
3465 /* We have to write in reasonably large chunks to be able
3466 * to fill large memory areas with any sane speed */
3467 const unsigned chunk_size = 16384;
3468 uint8_t *target_buf = malloc(chunk_size * data_size);
3469 if (!target_buf) {
3470 LOG_ERROR("Out of memory");
3471 return ERROR_FAIL;
3472 }
3473
3474 for (unsigned i = 0; i < chunk_size; i++) {
3475 switch (data_size) {
3476 case 8:
3477 target_buffer_set_u64(target, target_buf + i * data_size, b);
3478 break;
3479 case 4:
3480 target_buffer_set_u32(target, target_buf + i * data_size, b);
3481 break;
3482 case 2:
3483 target_buffer_set_u16(target, target_buf + i * data_size, b);
3484 break;
3485 case 1:
3486 target_buffer_set_u8(target, target_buf + i * data_size, b);
3487 break;
3488 default:
3489 exit(-1);
3490 }
3491 }
3492
3493 int retval = ERROR_OK;
3494
3495 for (unsigned x = 0; x < c; x += chunk_size) {
3496 unsigned current;
3497 current = c - x;
3498 if (current > chunk_size)
3499 current = chunk_size;
3500 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3501 if (retval != ERROR_OK)
3502 break;
3503 /* avoid GDB timeouts */
3504 keep_alive();
3505 }
3506 free(target_buf);
3507
3508 return retval;
3509 }
3510
3511
3512 COMMAND_HANDLER(handle_mw_command)
3513 {
3514 if (CMD_ARGC < 2)
3515 return ERROR_COMMAND_SYNTAX_ERROR;
3516 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3517 target_write_fn fn;
3518 if (physical) {
3519 CMD_ARGC--;
3520 CMD_ARGV++;
3521 fn = target_write_phys_memory;
3522 } else
3523 fn = target_write_memory;
3524 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3525 return ERROR_COMMAND_SYNTAX_ERROR;
3526
3527 target_addr_t address;
3528 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3529
3530 uint64_t value;
3531 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], value);
3532
3533 unsigned count = 1;
3534 if (CMD_ARGC == 3)
3535 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3536
3537 struct target *target = get_current_target(CMD_CTX);
3538 unsigned wordsize;
3539 switch (CMD_NAME[2]) {
3540 case 'd':
3541 wordsize = 8;
3542 break;
3543 case 'w':
3544 wordsize = 4;
3545 break;
3546 case 'h':
3547 wordsize = 2;
3548 break;
3549 case 'b':
3550 wordsize = 1;
3551 break;
3552 default:
3553 return ERROR_COMMAND_SYNTAX_ERROR;
3554 }
3555
3556 return target_fill_mem(target, address, fn, wordsize, value, count);
3557 }
3558
3559 static COMMAND_HELPER(parse_load_image_command, struct image *image,
3560 target_addr_t *min_address, target_addr_t *max_address)
3561 {
3562 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3563 return ERROR_COMMAND_SYNTAX_ERROR;
3564
3565 /* a base address isn't always necessary,
3566 * default to 0x0 (i.e. don't relocate) */
3567 if (CMD_ARGC >= 2) {
3568 target_addr_t addr;
3569 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3570 image->base_address = addr;
3571 image->base_address_set = true;
3572 } else
3573 image->base_address_set = false;
3574
3575 image->start_address_set = false;
3576
3577 if (CMD_ARGC >= 4)
3578 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3579 if (CMD_ARGC == 5) {
3580 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3581 /* use size (given) to find max (required) */
3582 *max_address += *min_address;
3583 }
3584
3585 if (*min_address > *max_address)
3586 return ERROR_COMMAND_SYNTAX_ERROR;
3587
3588 return ERROR_OK;
3589 }
3590
3591 COMMAND_HANDLER(handle_load_image_command)
3592 {
3593 uint8_t *buffer;
3594 size_t buf_cnt;
3595 uint32_t image_size;
3596 target_addr_t min_address = 0;
3597 target_addr_t max_address = -1;
3598 struct image image;
3599
3600 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
3601 &image, &min_address, &max_address);
3602 if (retval != ERROR_OK)
3603 return retval;
3604
3605 struct target *target = get_current_target(CMD_CTX);
3606
3607 struct duration bench;
3608 duration_start(&bench);
3609
3610 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3611 return ERROR_FAIL;
3612
3613 image_size = 0x0;
3614 retval = ERROR_OK;
3615 for (unsigned int i = 0; i < image.num_sections; i++) {
3616 buffer = malloc(image.sections[i].size);
3617 if (!buffer) {
3618 command_print(CMD,
3619 "error allocating buffer for section (%d bytes)",
3620 (int)(image.sections[i].size));
3621 retval = ERROR_FAIL;
3622 break;
3623 }
3624
3625 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3626 if (retval != ERROR_OK) {
3627 free(buffer);
3628 break;
3629 }
3630
3631 uint32_t offset = 0;
3632 uint32_t length = buf_cnt;
3633
3634 /* DANGER!!! beware of unsigned comparison here!!! */
3635
3636 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3637 (image.sections[i].base_address < max_address)) {
3638
3639 if (image.sections[i].base_address < min_address) {
3640 /* clip addresses below */
3641 offset += min_address-image.sections[i].base_address;
3642 length -= offset;
3643 }
3644
3645 if (image.sections[i].base_address + buf_cnt > max_address)
3646 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3647
3648 retval = target_write_buffer(target,
3649 image.sections[i].base_address + offset, length, buffer + offset);
3650 if (retval != ERROR_OK) {
3651 free(buffer);
3652 break;
3653 }
3654 image_size += length;
3655 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3656 (unsigned int)length,
3657 image.sections[i].base_address + offset);
3658 }
3659
3660 free(buffer);
3661 }
3662
3663 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3664 command_print(CMD, "downloaded %" PRIu32 " bytes "
3665 "in %fs (%0.3f KiB/s)", image_size,
3666 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3667 }
3668
3669 image_close(&image);
3670
3671 return retval;
3672
3673 }
3674
3675 COMMAND_HANDLER(handle_dump_image_command)
3676 {
3677 struct fileio *fileio;
3678 uint8_t *buffer;
3679 int retval, retvaltemp;
3680 target_addr_t address, size;
3681 struct duration bench;
3682 struct target *target = get_current_target(CMD_CTX);
3683
3684 if (CMD_ARGC != 3)
3685 return ERROR_COMMAND_SYNTAX_ERROR;
3686
3687 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3688 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3689
3690 uint32_t buf_size = (size > 4096) ? 4096 : size;
3691 buffer = malloc(buf_size);
3692 if (!buffer)
3693 return ERROR_FAIL;
3694
3695 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3696 if (retval != ERROR_OK) {
3697 free(buffer);
3698 return retval;
3699 }
3700
3701 duration_start(&bench);
3702
3703 while (size > 0) {
3704 size_t size_written;
3705 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3706 retval = target_read_buffer(target, address, this_run_size, buffer);
3707 if (retval != ERROR_OK)
3708 break;
3709
3710 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3711 if (retval != ERROR_OK)
3712 break;
3713
3714 size -= this_run_size;
3715 address += this_run_size;
3716 }
3717
3718 free(buffer);
3719
3720 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3721 size_t filesize;
3722 retval = fileio_size(fileio, &filesize);
3723 if (retval != ERROR_OK)
3724 return retval;
3725 command_print(CMD,
3726 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3727 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3728 }
3729
3730 retvaltemp = fileio_close(fileio);
3731 if (retvaltemp != ERROR_OK)
3732 return retvaltemp;
3733
3734 return retval;
3735 }
3736
3737 enum verify_mode {
3738 IMAGE_TEST = 0,
3739 IMAGE_VERIFY = 1,
3740 IMAGE_CHECKSUM_ONLY = 2
3741 };
3742
3743 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3744 {
3745 uint8_t *buffer;
3746 size_t buf_cnt;
3747 uint32_t image_size;
3748 int retval;
3749 uint32_t checksum = 0;
3750 uint32_t mem_checksum = 0;
3751
3752 struct image image;
3753
3754 struct target *target = get_current_target(CMD_CTX);
3755
3756 if (CMD_ARGC < 1)
3757 return ERROR_COMMAND_SYNTAX_ERROR;
3758
3759 if (!target) {
3760 LOG_ERROR("no target selected");
3761 return ERROR_FAIL;
3762 }
3763
3764 struct duration bench;
3765 duration_start(&bench);
3766
3767 if (CMD_ARGC >= 2) {
3768 target_addr_t addr;
3769 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3770 image.base_address = addr;
3771 image.base_address_set = true;
3772 } else {
3773 image.base_address_set = false;
3774 image.base_address = 0x0;
3775 }
3776
3777 image.start_address_set = false;
3778
3779 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3780 if (retval != ERROR_OK)
3781 return retval;
3782
3783 image_size = 0x0;
3784 int diffs = 0;
3785 retval = ERROR_OK;
3786 for (unsigned int i = 0; i < image.num_sections; i++) {
3787 buffer = malloc(image.sections[i].size);
3788 if (!buffer) {
3789 command_print(CMD,
3790 "error allocating buffer for section (%" PRIu32 " bytes)",
3791 image.sections[i].size);
3792 break;
3793 }
3794 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3795 if (retval != ERROR_OK) {
3796 free(buffer);
3797 break;
3798 }
3799
3800 if (verify >= IMAGE_VERIFY) {
3801 /* calculate checksum of image */
3802 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3803 if (retval != ERROR_OK) {
3804 free(buffer);
3805 break;
3806 }
3807
3808 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3809 if (retval != ERROR_OK) {
3810 free(buffer);
3811 break;
3812 }
3813 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3814 LOG_ERROR("checksum mismatch");
3815 free(buffer);
3816 retval = ERROR_FAIL;
3817 goto done;
3818 }
3819 if (checksum != mem_checksum) {
3820 /* failed crc checksum, fall back to a binary compare */
3821 uint8_t *data;
3822
3823 if (diffs == 0)
3824 LOG_ERROR("checksum mismatch - attempting binary compare");
3825
3826 data = malloc(buf_cnt);
3827
3828 retval = target_read_buffer(target, image.sections[i].base_address, buf_cnt, data);
3829 if (retval == ERROR_OK) {
3830 uint32_t t;
3831 for (t = 0; t < buf_cnt; t++) {
3832 if (data[t] != buffer[t]) {
3833 command_print(CMD,
3834 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3835 diffs,
3836 (unsigned)(t + image.sections[i].base_address),
3837 data[t],
3838 buffer[t]);
3839 if (diffs++ >= 127) {
3840 command_print(CMD, "More than 128 errors, the rest are not printed.");
3841 free(data);
3842 free(buffer);
3843 goto done;
3844 }
3845 }
3846 keep_alive();
3847 }
3848 }
3849 free(data);
3850 }
3851 } else {
3852 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3853 image.sections[i].base_address,
3854 buf_cnt);
3855 }
3856
3857 free(buffer);
3858 image_size += buf_cnt;
3859 }
3860 if (diffs > 0)
3861 command_print(CMD, "No more differences found.");
3862 done:
3863 if (diffs > 0)
3864 retval = ERROR_FAIL;
3865 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
3866 command_print(CMD, "verified %" PRIu32 " bytes "
3867 "in %fs (%0.3f KiB/s)", image_size,
3868 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3869 }
3870
3871 image_close(&image);
3872
3873 return retval;
3874 }
3875
3876 COMMAND_HANDLER(handle_verify_image_checksum_command)
3877 {
3878 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3879 }
3880
3881 COMMAND_HANDLER(handle_verify_image_command)
3882 {
3883 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3884 }
3885
3886 COMMAND_HANDLER(handle_test_image_command)
3887 {
3888 return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3889 }
3890
3891 static int handle_bp_command_list(struct command_invocation *cmd)
3892 {
3893 struct target *target = get_current_target(cmd->ctx);
3894 struct breakpoint *breakpoint = target->breakpoints;
3895 while (breakpoint) {
3896 if (breakpoint->type == BKPT_SOFT) {
3897 char *buf = buf_to_hex_str(breakpoint->orig_instr,
3898 breakpoint->length);
3899 command_print(cmd, "Software breakpoint(IVA): addr=" TARGET_ADDR_FMT ", len=0x%x, orig_instr=0x%s",
3900 breakpoint->address,
3901 breakpoint->length,
3902 buf);
3903 free(buf);
3904 } else {
3905 if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3906 command_print(cmd, "Context breakpoint: asid=0x%8.8" PRIx32 ", len=0x%x, num=%u",
3907 breakpoint->asid,
3908 breakpoint->length, breakpoint->number);
3909 else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3910 command_print(cmd, "Hybrid breakpoint(IVA): addr=" TARGET_ADDR_FMT ", len=0x%x, num=%u",
3911 breakpoint->address,
3912 breakpoint->length, breakpoint->number);
3913 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3914 breakpoint->asid);
3915 } else
3916 command_print(cmd, "Hardware breakpoint(IVA): addr=" TARGET_ADDR_FMT ", len=0x%x, num=%u",
3917 breakpoint->address,
3918 breakpoint->length, breakpoint->number);
3919 }
3920
3921 breakpoint = breakpoint->next;
3922 }
3923 return ERROR_OK;
3924 }
3925
3926 static int handle_bp_command_set(struct command_invocation *cmd,
3927 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3928 {
3929 struct target *target = get_current_target(cmd->ctx);
3930 int retval;
3931
3932 if (asid == 0) {
3933 retval = breakpoint_add(target, addr, length, hw);
3934 /* error is always logged in breakpoint_add(), do not print it again */
3935 if (retval == ERROR_OK)
3936 command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3937
3938 } else if (addr == 0) {
3939 if (!target->type->add_context_breakpoint) {
3940 LOG_TARGET_ERROR(target, "Context breakpoint not available");
3941 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3942 }
3943 retval = context_breakpoint_add(target, asid, length, hw);
3944 /* error is always logged in context_breakpoint_add(), do not print it again */
3945 if (retval == ERROR_OK)
3946 command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3947
3948 } else {
3949 if (!target->type->add_hybrid_breakpoint) {
3950 LOG_TARGET_ERROR(target, "Hybrid breakpoint not available");
3951 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3952 }
3953 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3954 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
3955 if (retval == ERROR_OK)
3956 command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3957 }
3958 return retval;
3959 }
3960
3961 COMMAND_HANDLER(handle_bp_command)
3962 {
3963 target_addr_t addr;
3964 uint32_t asid;
3965 uint32_t length;
3966 int hw = BKPT_SOFT;
3967
3968 switch (CMD_ARGC) {
3969 case 0:
3970 return handle_bp_command_list(CMD);
3971
3972 case 2:
3973 asid = 0;
3974 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3975 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3976 return handle_bp_command_set(CMD, addr, asid, length, hw);
3977
3978 case 3:
3979 if (strcmp(CMD_ARGV[2], "hw") == 0) {
3980 hw = BKPT_HARD;
3981 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3982 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3983 asid = 0;
3984 return handle_bp_command_set(CMD, addr, asid, length, hw);
3985 } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3986 hw = BKPT_HARD;
3987 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3988 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3989 addr = 0;
3990 return handle_bp_command_set(CMD, addr, asid, length, hw);
3991 }
3992 /* fallthrough */
3993 case 4:
3994 hw = BKPT_HARD;
3995 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3996 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3997 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3998 return handle_bp_command_set(CMD, addr, asid, length, hw);
3999
4000 default:
4001 return ERROR_COMMAND_SYNTAX_ERROR;
4002 }
4003 }
4004
4005 COMMAND_HANDLER(handle_rbp_command)
4006 {
4007 int retval;
4008
4009 if (CMD_ARGC != 1)
4010 return ERROR_COMMAND_SYNTAX_ERROR;
4011
4012 struct target *target = get_current_target(CMD_CTX);
4013
4014 if (!strcmp(CMD_ARGV[0], "all")) {
4015 retval = breakpoint_remove_all(target);
4016
4017 if (retval != ERROR_OK) {
4018 command_print(CMD, "Error encountered during removal of all breakpoints.");
4019 command_print(CMD, "Some breakpoints may have remained set.");
4020 }
4021 } else {
4022 target_addr_t addr;
4023 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4024
4025 retval = breakpoint_remove(target, addr);
4026
4027 if (retval != ERROR_OK)
4028 command_print(CMD, "Error during removal of breakpoint at address " TARGET_ADDR_FMT, addr);
4029 }
4030
4031 return retval;
4032 }
4033
4034 COMMAND_HANDLER(handle_wp_command)
4035 {
4036 struct target *target = get_current_target(CMD_CTX);
4037
4038 if (CMD_ARGC == 0) {
4039 struct watchpoint *watchpoint = target->watchpoints;
4040
4041 while (watchpoint) {
4042 char wp_type = (watchpoint->rw == WPT_READ ? 'r' : (watchpoint->rw == WPT_WRITE ? 'w' : 'a'));
4043 command_print(CMD, "address: " TARGET_ADDR_FMT
4044 ", len: 0x%8.8" PRIx32
4045 ", r/w/a: %c, value: 0x%8.8" PRIx64
4046 ", mask: 0x%8.8" PRIx64,
4047 watchpoint->address,
4048 watchpoint->length,
4049 wp_type,
4050 watchpoint->value,
4051 watchpoint->mask);
4052 watchpoint = watchpoint->next;
4053 }
4054 return ERROR_OK;
4055 }
4056
4057 enum watchpoint_rw type = WPT_ACCESS;
4058 target_addr_t addr = 0;
4059 uint32_t length = 0;
4060 uint64_t data_value = 0x0;
4061 uint64_t data_mask = WATCHPOINT_IGNORE_DATA_VALUE_MASK;
4062 bool mask_specified = false;
4063
4064 switch (CMD_ARGC) {
4065 case 5:
4066 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[4], data_mask);
4067 mask_specified = true;
4068 /* fall through */
4069 case 4:
4070 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[3], data_value);
4071 // if user specified only data value without mask - the mask should be 0
4072 if (!mask_specified)
4073 data_mask = 0;
4074 /* fall through */
4075 case 3:
4076 switch (CMD_ARGV[2][0]) {
4077 case 'r':
4078 type = WPT_READ;
4079 break;
4080 case 'w':
4081 type = WPT_WRITE;
4082 break;
4083 case 'a':
4084 type = WPT_ACCESS;
4085 break;
4086 default:
4087 LOG_TARGET_ERROR(target, "invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
4088 return ERROR_COMMAND_SYNTAX_ERROR;
4089 }
4090 /* fall through */
4091 case 2:
4092 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
4093 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4094 break;
4095
4096 default:
4097 return ERROR_COMMAND_SYNTAX_ERROR;
4098 }
4099
4100 int retval = watchpoint_add(target, addr, length, type,
4101 data_value, data_mask);
4102 if (retval != ERROR_OK)
4103 LOG_TARGET_ERROR(target, "Failure setting watchpoints");
4104
4105 return retval;
4106 }
4107
4108 COMMAND_HANDLER(handle_rwp_command)
4109 {
4110 int retval;
4111
4112 if (CMD_ARGC != 1)
4113 return ERROR_COMMAND_SYNTAX_ERROR;
4114
4115 struct target *target = get_current_target(CMD_CTX);
4116 if (!strcmp(CMD_ARGV[0], "all")) {
4117 retval = watchpoint_remove_all(target);
4118
4119 if (retval != ERROR_OK) {
4120 command_print(CMD, "Error encountered during removal of all watchpoints.");
4121 command_print(CMD, "Some watchpoints may have remained set.");
4122 }
4123 } else {
4124 target_addr_t addr;
4125 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
4126
4127 retval = watchpoint_remove(target, addr);
4128
4129 if (retval != ERROR_OK)
4130 command_print(CMD, "Error during removal of watchpoint at address " TARGET_ADDR_FMT, addr);
4131 }
4132
4133 return retval;
4134 }
4135
4136 /**
4137 * Translate a virtual address to a physical address.
4138 *
4139 * The low-level target implementation must have logged a detailed error
4140 * which is forwarded to telnet/GDB session.
4141 */
4142 COMMAND_HANDLER(handle_virt2phys_command)
4143 {
4144 if (CMD_ARGC != 1)
4145 return ERROR_COMMAND_SYNTAX_ERROR;
4146
4147 target_addr_t va;
4148 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
4149 target_addr_t pa;
4150
4151 struct target *target = get_current_target(CMD_CTX);
4152 int retval = target->type->virt2phys(target, va, &pa);
4153 if (retval == ERROR_OK)
4154 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
4155
4156 return retval;
4157 }
4158
4159 static void write_data(FILE *f, const void *data, size_t len)
4160 {
4161 size_t written = fwrite(data, 1, len, f);
4162 if (written != len)
4163 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
4164 }
4165
4166 static void write_long(FILE *f, int l, struct target *target)
4167 {
4168 uint8_t val[4];
4169
4170 target_buffer_set_u32(target, val, l);
4171 write_data(f, val, 4);
4172 }
4173
4174 static void write_string(FILE *f, char *s)
4175 {
4176 write_data(f, s, strlen(s));
4177 }
4178
4179 typedef unsigned char UNIT[2]; /* unit of profiling */
4180
4181 /* Dump a gmon.out histogram file. */
4182 static void write_gmon(uint32_t *samples, uint32_t sample_num, const char *filename, bool with_range,
4183 uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
4184 {
4185 uint32_t i;
4186 FILE *f = fopen(filename, "w");
4187 if (!f)
4188 return;
4189 write_string(f, "gmon");
4190 write_long(f, 0x00000001, target); /* Version */
4191 write_long(f, 0, target); /* padding */
4192 write_long(f, 0, target); /* padding */
4193 write_long(f, 0, target); /* padding */
4194
4195 uint8_t zero = 0; /* GMON_TAG_TIME_HIST */
4196 write_data(f, &zero, 1);
4197
4198 /* figure out bucket size */
4199 uint32_t min;
4200 uint32_t max;
4201 if (with_range) {
4202 min = start_address;
4203 max = end_address;
4204 } else {
4205 min = samples[0];
4206 max = samples[0];
4207 for (i = 0; i < sample_num; i++) {
4208 if (min > samples[i])
4209 min = samples[i];
4210 if (max < samples[i])
4211 max = samples[i];
4212 }
4213
4214 /* max should be (largest sample + 1)
4215 * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
4216 if (max < UINT32_MAX)
4217 max++;
4218
4219 /* gprof requires (max - min) >= 2 */
4220 while ((max - min) < 2) {
4221 if (max < UINT32_MAX)
4222 max++;
4223 else
4224 min--;
4225 }
4226 }
4227
4228 uint32_t address_space = max - min;
4229
4230 /* FIXME: What is the reasonable number of buckets?
4231 * The profiling result will be more accurate if there are enough buckets. */
4232 static const uint32_t max_buckets = 128 * 1024; /* maximum buckets. */
4233 uint32_t num_buckets = address_space / sizeof(UNIT);
4234 if (num_buckets > max_buckets)
4235 num_buckets = max_buckets;
4236 int *buckets = malloc(sizeof(int) * num_buckets);
4237 if (!buckets) {
4238 fclose(f);
4239 return;
4240 }
4241 memset(buckets, 0, sizeof(int) * num_buckets);
4242 for (i = 0; i < sample_num; i++) {
4243 uint32_t address = samples[i];
4244
4245 if ((address < min) || (max <= address))
4246 continue;
4247
4248 long long a = address - min;
4249 long long b = num_buckets;
4250 long long c = address_space;
4251 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4252 buckets[index_t]++;
4253 }
4254
4255 /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4256 write_long(f, min, target); /* low_pc */
4257 write_long(f, max, target); /* high_pc */
4258 write_long(f, num_buckets, target); /* # of buckets */
4259 float sample_rate = sample_num / (duration_ms / 1000.0);
4260 write_long(f, sample_rate, target);
4261 write_string(f, "seconds");
4262 for (i = 0; i < (15-strlen("seconds")); i++)
4263 write_data(f, &zero, 1);
4264 write_string(f, "s");
4265
4266 /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4267
4268 char *data = malloc(2 * num_buckets);
4269 if (data) {
4270 for (i = 0; i < num_buckets; i++) {
4271 int val;
4272 val = buckets[i];
4273 if (val > 65535)
4274 val = 65535;
4275 data[i * 2] = val&0xff;
4276 data[i * 2 + 1] = (val >> 8) & 0xff;
4277 }
4278 free(buckets);
4279 write_data(f, data, num_buckets * 2);
4280 free(data);
4281 } else
4282 free(buckets);
4283
4284 fclose(f);
4285 }
4286
4287 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4288 * which will be used as a random sampling of PC */
4289 COMMAND_HANDLER(handle_profile_command)
4290 {
4291 struct target *target = get_current_target(CMD_CTX);
4292
4293 if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4294 return ERROR_COMMAND_SYNTAX_ERROR;
4295
4296 const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4297 uint32_t offset;
4298 uint32_t num_of_samples;
4299 int retval = ERROR_OK;
4300 bool halted_before_profiling = target->state == TARGET_HALTED;
4301
4302 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4303
4304 uint32_t start_address = 0;
4305 uint32_t end_address = 0;
4306 bool with_range = false;
4307 if (CMD_ARGC == 4) {
4308 with_range = true;
4309 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4310 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4311 if (start_address > end_address || (end_address - start_address) < 2) {
4312 command_print(CMD, "Error: end - start < 2");
4313 return ERROR_COMMAND_ARGUMENT_INVALID;
4314 }
4315 }
4316
4317 uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4318 if (!samples) {
4319 LOG_ERROR("No memory to store samples.");
4320 return ERROR_FAIL;
4321 }
4322
4323 uint64_t timestart_ms = timeval_ms();
4324 /**
4325 * Some cores let us sample the PC without the
4326 * annoying halt/resume step; for example, ARMv7 PCSR.
4327 * Provide a way to use that more efficient mechanism.
4328 */
4329 retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4330 &num_of_samples, offset);
4331 if (retval != ERROR_OK) {
4332 free(samples);
4333 return retval;
4334 }
4335 uint32_t duration_ms = timeval_ms() - timestart_ms;
4336
4337 assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4338
4339 retval = target_poll(target);
4340 if (retval != ERROR_OK) {
4341 free(samples);
4342 return retval;
4343 }
4344
4345 if (target->state == TARGET_RUNNING && halted_before_profiling) {
4346 /* The target was halted before we started and is running now. Halt it,
4347 * for consistency. */
4348 retval = target_halt(target);
4349 if (retval != ERROR_OK) {
4350 free(samples);
4351 return retval;
4352 }
4353 } else if (target->state == TARGET_HALTED && !halted_before_profiling) {
4354 /* The target was running before we started and is halted now. Resume
4355 * it, for consistency. */
4356 retval = target_resume(target, 1, 0, 0, 0);
4357 if (retval != ERROR_OK) {
4358 free(samples);
4359 return retval;
4360 }
4361 }
4362
4363 retval = target_poll(target);
4364 if (retval != ERROR_OK) {
4365 free(samples);
4366 return retval;
4367 }
4368
4369 write_gmon(samples, num_of_samples, CMD_ARGV[1],
4370 with_range, start_address, end_address, target, duration_ms);
4371 command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4372
4373 free(samples);
4374 return retval;
4375 }
4376
4377 static int new_u64_array_element(Jim_Interp *interp, const char *varname, int idx, uint64_t val)
4378 {
4379 char *namebuf;
4380 Jim_Obj *obj_name, *obj_val;
4381 int result;
4382
4383 namebuf = alloc_printf("%s(%d)", varname, idx);
4384 if (!namebuf)
4385 return JIM_ERR;
4386
4387 obj_name = Jim_NewStringObj(interp, namebuf, -1);
4388 jim_wide wide_val = val;
4389 obj_val = Jim_NewWideObj(interp, wide_val);
4390 if (!obj_name || !obj_val) {
4391 free(namebuf);
4392 return JIM_ERR;
4393 }
4394
4395 Jim_IncrRefCount(obj_name);
4396 Jim_IncrRefCount(obj_val);
4397 result = Jim_SetVariable(interp, obj_name, obj_val);
4398 Jim_DecrRefCount(interp, obj_name);
4399 Jim_DecrRefCount(interp, obj_val);
4400 free(namebuf);
4401 /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4402 return result;
4403 }
4404
4405 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4406 {
4407 int e;
4408
4409 LOG_WARNING("DEPRECATED! use 'read_memory' not 'mem2array'");
4410
4411 /* argv[0] = name of array to receive the data
4412 * argv[1] = desired element width in bits
4413 * argv[2] = memory address
4414 * argv[3] = count of times to read
4415 * argv[4] = optional "phys"
4416 */
4417 if (argc < 4 || argc > 5) {
4418 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4419 return JIM_ERR;
4420 }
4421
4422 /* Arg 0: Name of the array variable */
4423 const char *varname = Jim_GetString(argv[0], NULL);
4424
4425 /* Arg 1: Bit width of one element */
4426 long l;
4427 e = Jim_GetLong(interp, argv[1], &l);
4428 if (e != JIM_OK)
4429 return e;
4430 const unsigned int width_bits = l;
4431
4432 if (width_bits != 8 &&
4433 width_bits != 16 &&
4434 width_bits != 32 &&
4435 width_bits != 64) {
4436 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4437 Jim_AppendStrings(interp, Jim_GetResult(interp),
4438 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4439 return JIM_ERR;
4440 }
4441 const unsigned int width = width_bits / 8;
4442
4443 /* Arg 2: Memory address */
4444 jim_wide wide_addr;
4445 e = Jim_GetWide(interp, argv[2], &wide_addr);
4446 if (e != JIM_OK)
4447 return e;
4448 target_addr_t addr = (target_addr_t)wide_addr;
4449
4450 /* Arg 3: Number of elements to read */
4451 e = Jim_GetLong(interp, argv[3], &l);
4452 if (e != JIM_OK)
4453 return e;
4454 size_t len = l;
4455
4456 /* Arg 4: phys */
4457 bool is_phys = false;
4458 if (argc > 4) {
4459 int str_len = 0;
4460 const char *phys = Jim_GetString(argv[4], &str_len);
4461 if (!strncmp(phys, "phys", str_len))
4462 is_phys = true;
4463 else
4464 return JIM_ERR;
4465 }
4466
4467 /* Argument checks */
4468 if (len == 0) {
4469 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4470 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4471 return JIM_ERR;
4472 }
4473 if ((addr + (len * width)) < addr) {
4474 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4475 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4476 return JIM_ERR;
4477 }
4478 if (len > 65536) {
4479 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4480 Jim_AppendStrings(interp, Jim_GetResult(interp),
4481 "mem2array: too large read request, exceeds 64K items", NULL);
4482 return JIM_ERR;
4483 }
4484
4485 if ((width == 1) ||
4486 ((width == 2) && ((addr & 1) == 0)) ||
4487 ((width == 4) && ((addr & 3) == 0)) ||
4488 ((width == 8) && ((addr & 7) == 0))) {
4489 /* alignment correct */
4490 } else {
4491 char buf[100];
4492 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4493 sprintf(buf, "mem2array address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4494 addr,
4495 width);
4496 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4497 return JIM_ERR;
4498 }
4499
4500 /* Transfer loop */
4501
4502 /* index counter */
4503 size_t idx = 0;
4504
4505 const size_t buffersize = 4096;
4506 uint8_t *buffer = malloc(buffersize);
4507 if (!buffer)
4508 return JIM_ERR;
4509
4510 /* assume ok */
4511 e = JIM_OK;
4512 while (len) {
4513 /* Slurp... in buffer size chunks */
4514 const unsigned int max_chunk_len = buffersize / width;
4515 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4516
4517 int retval;
4518 if (is_phys)
4519 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4520 else
4521 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4522 if (retval != ERROR_OK) {
4523 /* BOO !*/
4524 LOG_ERROR("mem2array: Read @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4525 addr,
4526 width,
4527 chunk_len);
4528 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4529 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4530 e = JIM_ERR;
4531 break;
4532 } else {
4533 for (size_t i = 0; i < chunk_len ; i++, idx++) {
4534 uint64_t v = 0;
4535 switch (width) {
4536 case 8:
4537 v = target_buffer_get_u64(target, &buffer[i*width]);
4538 break;
4539 case 4:
4540 v = target_buffer_get_u32(target, &buffer[i*width]);
4541 break;
4542 case 2:
4543 v = target_buffer_get_u16(target, &buffer[i*width]);
4544 break;
4545 case 1:
4546 v = buffer[i] & 0x0ff;
4547 break;
4548 }
4549 new_u64_array_element(interp, varname, idx, v);
4550 }
4551 len -= chunk_len;
4552 addr += chunk_len * width;
4553 }
4554 }
4555
4556 free(buffer);
4557
4558 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4559
4560 return e;
4561 }
4562
4563 COMMAND_HANDLER(handle_target_read_memory)
4564 {
4565 /*
4566 * CMD_ARGV[0] = memory address
4567 * CMD_ARGV[1] = desired element width in bits
4568 * CMD_ARGV[2] = number of elements to read
4569 * CMD_ARGV[3] = optional "phys"
4570 */
4571
4572 if (CMD_ARGC < 3 || CMD_ARGC > 4)
4573 return ERROR_COMMAND_SYNTAX_ERROR;
4574
4575 /* Arg 1: Memory address. */
4576 target_addr_t addr;
4577 COMMAND_PARSE_NUMBER(u64, CMD_ARGV[0], addr);
4578
4579 /* Arg 2: Bit width of one element. */
4580 unsigned int width_bits;
4581 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], width_bits);
4582
4583 /* Arg 3: Number of elements to read. */
4584 unsigned int count;
4585 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
4586
4587 /* Arg 4: Optional 'phys'. */
4588 bool is_phys = false;
4589 if (CMD_ARGC == 4) {
4590 if (strcmp(CMD_ARGV[3], "phys")) {
4591 command_print(CMD, "invalid argument '%s', must be 'phys'", CMD_ARGV[3]);
4592 return ERROR_COMMAND_ARGUMENT_INVALID;
4593 }
4594
4595 is_phys = true;
4596 }
4597
4598 switch (width_bits) {
4599 case 8:
4600 case 16:
4601 case 32:
4602 case 64:
4603 break;
4604 default:
4605 command_print(CMD, "invalid width, must be 8, 16, 32 or 64");
4606 return ERROR_COMMAND_ARGUMENT_INVALID;
4607 }
4608
4609 const unsigned int width = width_bits / 8;
4610
4611 if ((addr + (count * width)) < addr) {
4612 command_print(CMD, "read_memory: addr + count wraps to zero");
4613 return ERROR_COMMAND_ARGUMENT_INVALID;
4614 }
4615
4616 if (count > 65536) {
4617 command_print(CMD, "read_memory: too large read request, exceeds 64K elements");
4618 return ERROR_COMMAND_ARGUMENT_INVALID;
4619 }
4620
4621 struct target *target = get_current_target(CMD_CTX);
4622
4623 const size_t buffersize = 4096;
4624 uint8_t *buffer = malloc(buffersize);
4625
4626 if (!buffer) {
4627 LOG_ERROR("Failed to allocate memory");
4628 return ERROR_FAIL;
4629 }
4630
4631 char *separator = "";
4632 while (count > 0) {
4633 const unsigned int max_chunk_len = buffersize / width;
4634 const size_t chunk_len = MIN(count, max_chunk_len);
4635
4636 int retval;
4637
4638 if (is_phys)
4639 retval = target_read_phys_memory(target, addr, width, chunk_len, buffer);
4640 else
4641 retval = target_read_memory(target, addr, width, chunk_len, buffer);
4642
4643 if (retval != ERROR_OK) {
4644 LOG_DEBUG("read_memory: read at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
4645 addr, width_bits, chunk_len);
4646 /*
4647 * FIXME: we append the errmsg to the list of value already read.
4648 * Add a way to flush and replace old output, but LOG_DEBUG() it
4649 */
4650 command_print(CMD, "read_memory: failed to read memory");
4651 free(buffer);
4652 return retval;
4653 }
4654
4655 for (size_t i = 0; i < chunk_len ; i++) {
4656 uint64_t v = 0;
4657
4658 switch (width) {
4659 case 8:
4660 v = target_buffer_get_u64(target, &buffer[i * width]);
4661 break;
4662 case 4:
4663 v = target_buffer_get_u32(target, &buffer[i * width]);
4664 break;
4665 case 2:
4666 v = target_buffer_get_u16(target, &buffer[i * width]);
4667 break;
4668 case 1:
4669 v = buffer[i];
4670 break;
4671 }
4672
4673 command_print_sameline(CMD, "%s0x%" PRIx64, separator, v);
4674 separator = " ";
4675 }
4676
4677 count -= chunk_len;
4678 addr += chunk_len * width;
4679 }
4680
4681 free(buffer);
4682
4683 return ERROR_OK;
4684 }
4685
4686 static int get_u64_array_element(Jim_Interp *interp, const char *varname, size_t idx, uint64_t *val)
4687 {
4688 char *namebuf = alloc_printf("%s(%zu)", varname, idx);
4689 if (!namebuf)
4690 return JIM_ERR;
4691
4692 Jim_Obj *obj_name = Jim_NewStringObj(interp, namebuf, -1);
4693 if (!obj_name) {
4694 free(namebuf);
4695 return JIM_ERR;
4696 }
4697
4698 Jim_IncrRefCount(obj_name);
4699 Jim_Obj *obj_val = Jim_GetVariable(interp, obj_name, JIM_ERRMSG);
4700 Jim_DecrRefCount(interp, obj_name);
4701 free(namebuf);
4702 if (!obj_val)
4703 return JIM_ERR;
4704
4705 jim_wide wide_val;
4706 int result = Jim_GetWide(interp, obj_val, &wide_val);
4707 *val = wide_val;
4708 return result;
4709 }
4710
4711 static int target_array2mem(Jim_Interp *interp, struct target *target,
4712 int argc, Jim_Obj *const *argv)
4713 {
4714 int e;
4715
4716 LOG_WARNING("DEPRECATED! use 'write_memory' not 'array2mem'");
4717
4718 /* argv[0] = name of array from which to read the data
4719 * argv[1] = desired element width in bits
4720 * argv[2] = memory address
4721 * argv[3] = number of elements to write
4722 * argv[4] = optional "phys"
4723 */
4724 if (argc < 4 || argc > 5) {
4725 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4726 return JIM_ERR;
4727 }
4728
4729 /* Arg 0: Name of the array variable */
4730 const char *varname = Jim_GetString(argv[0], NULL);
4731
4732 /* Arg 1: Bit width of one element */
4733 long l;
4734 e = Jim_GetLong(interp, argv[1], &l);
4735 if (e != JIM_OK)
4736 return e;
4737 const unsigned int width_bits = l;
4738
4739 if (width_bits != 8 &&
4740 width_bits != 16 &&
4741 width_bits != 32 &&
4742 width_bits != 64) {
4743 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4744 Jim_AppendStrings(interp, Jim_GetResult(interp),
4745 "Invalid width param. Must be one of: 8, 16, 32 or 64.", NULL);
4746 return JIM_ERR;
4747 }
4748 const unsigned int width = width_bits / 8;
4749
4750 /* Arg 2: Memory address */
4751 jim_wide wide_addr;
4752 e = Jim_GetWide(interp, argv[2], &wide_addr);
4753 if (e != JIM_OK)
4754 return e;
4755 target_addr_t addr = (target_addr_t)wide_addr;
4756
4757 /* Arg 3: Number of elements to write */
4758 e = Jim_GetLong(interp, argv[3], &l);
4759 if (e != JIM_OK)
4760 return e;
4761 size_t len = l;
4762
4763 /* Arg 4: Phys */
4764 bool is_phys = false;
4765 if (argc > 4) {
4766 int str_len = 0;
4767 const char *phys = Jim_GetString(argv[4], &str_len);
4768 if (!strncmp(phys, "phys", str_len))
4769 is_phys = true;
4770 else
4771 return JIM_ERR;
4772 }
4773
4774 /* Argument checks */
4775 if (len == 0) {
4776 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4777 Jim_AppendStrings(interp, Jim_GetResult(interp),
4778 "array2mem: zero width read?", NULL);
4779 return JIM_ERR;
4780 }
4781
4782 if ((addr + (len * width)) < addr) {
4783 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4784 Jim_AppendStrings(interp, Jim_GetResult(interp),
4785 "array2mem: addr + len - wraps to zero?", NULL);
4786 return JIM_ERR;
4787 }
4788
4789 if (len > 65536) {
4790 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4791 Jim_AppendStrings(interp, Jim_GetResult(interp),
4792 "array2mem: too large memory write request, exceeds 64K items", NULL);
4793 return JIM_ERR;
4794 }
4795
4796 if ((width == 1) ||
4797 ((width == 2) && ((addr & 1) == 0)) ||
4798 ((width == 4) && ((addr & 3) == 0)) ||
4799 ((width == 8) && ((addr & 7) == 0))) {
4800 /* alignment correct */
4801 } else {
4802 char buf[100];
4803 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4804 sprintf(buf, "array2mem address: " TARGET_ADDR_FMT " is not aligned for %" PRIu32 " byte reads",
4805 addr,
4806 width);
4807 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4808 return JIM_ERR;
4809 }
4810
4811 /* Transfer loop */
4812
4813 /* assume ok */
4814 e = JIM_OK;
4815
4816 const size_t buffersize = 4096;
4817 uint8_t *buffer = malloc(buffersize);
4818 if (!buffer)
4819 return JIM_ERR;
4820
4821 /* index counter */
4822 size_t idx = 0;
4823
4824 while (len) {
4825 /* Slurp... in buffer size chunks */
4826 const unsigned int max_chunk_len = buffersize / width;
4827
4828 const size_t chunk_len = MIN(len, max_chunk_len); /* in elements.. */
4829
4830 /* Fill the buffer */
4831 for (size_t i = 0; i < chunk_len; i++, idx++) {
4832 uint64_t v = 0;
4833 if (get_u64_array_element(interp, varname, idx, &v) != JIM_OK) {
4834 free(buffer);
4835 return JIM_ERR;
4836 }
4837 switch (width) {
4838 case 8:
4839 target_buffer_set_u64(target, &buffer[i * width], v);
4840 break;
4841 case 4:
4842 target_buffer_set_u32(target, &buffer[i * width], v);
4843 break;
4844 case 2:
4845 target_buffer_set_u16(target, &buffer[i * width], v);
4846 break;
4847 case 1:
4848 buffer[i] = v & 0x0ff;
4849 break;
4850 }
4851 }
4852 len -= chunk_len;
4853
4854 /* Write the buffer to memory */
4855 int retval;
4856 if (is_phys)
4857 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
4858 else
4859 retval = target_write_memory(target, addr, width, chunk_len, buffer);
4860 if (retval != ERROR_OK) {
4861 /* BOO !*/
4862 LOG_ERROR("array2mem: Write @ " TARGET_ADDR_FMT ", w=%u, cnt=%zu, failed",
4863 addr,
4864 width,
4865 chunk_len);
4866 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4867 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4868 e = JIM_ERR;
4869 break;
4870 }
4871 addr += chunk_len * width;
4872 }
4873
4874 free(buffer);
4875
4876 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4877
4878 return e;
4879 }
4880
4881 static int target_jim_write_memory(Jim_Interp *interp, int argc,
4882 Jim_Obj * const *argv)
4883 {
4884 /*
4885 * argv[1] = memory address
4886 * argv[2] = desired element width in bits
4887 * argv[3] = list of data to write
4888 * argv[4] = optional "phys"
4889 */
4890
4891 if (argc < 4 || argc > 5) {
4892 Jim_WrongNumArgs(interp, 1, argv, "address width data ['phys']");
4893 return JIM_ERR;
4894 }
4895
4896 /* Arg 1: Memory address. */
4897 int e;
4898 jim_wide wide_addr;
4899 e = Jim_GetWide(interp, argv[1], &wide_addr);
4900
4901 if (e != JIM_OK)
4902 return e;
4903
4904 target_addr_t addr = (target_addr_t)wide_addr;
4905
4906 /* Arg 2: Bit width of one element. */
4907 long l;
4908 e = Jim_GetLong(interp, argv[2], &l);
4909
4910 if (e != JIM_OK)
4911 return e;
4912
4913 const unsigned int width_bits = l;
4914 size_t count = Jim_ListLength(interp, argv[3]);
4915
4916 /* Arg 4: Optional 'phys'. */
4917 bool is_phys = false;
4918
4919 if (argc > 4) {
4920 const char *phys = Jim_GetString(argv[4], NULL);
4921
4922 if (strcmp(phys, "phys")) {
4923 Jim_SetResultFormatted(interp, "invalid argument '%s', must be 'phys'", phys);
4924 return JIM_ERR;
4925 }
4926
4927 is_phys = true;
4928 }
4929
4930 switch (width_bits) {
4931 case 8:
4932 case 16:
4933 case 32:
4934 case 64:
4935 break;
4936 default:
4937 Jim_SetResultString(interp, "invalid width, must be 8, 16, 32 or 64", -1);
4938 return JIM_ERR;
4939 }
4940
4941 const unsigned int width = width_bits / 8;
4942
4943 if ((addr + (count * width)) < addr) {
4944 Jim_SetResultString(interp, "write_memory: addr + len wraps to zero", -1);
4945 return JIM_ERR;
4946 }
4947
4948 if (count > 65536) {
4949 Jim_SetResultString(interp, "write_memory: too large memory write request, exceeds 64K elements", -1);
4950 return JIM_ERR;
4951 }
4952
4953 struct command_context *cmd_ctx = current_command_context(interp);
4954 assert(cmd_ctx != NULL);
4955 struct target *target = get_current_target(cmd_ctx);
4956
4957 const size_t buffersize = 4096;
4958 uint8_t *buffer = malloc(buffersize);
4959
4960 if (!buffer) {
4961 LOG_ERROR("Failed to allocate memory");
4962 return JIM_ERR;
4963 }
4964
4965 size_t j = 0;
4966
4967 while (count > 0) {
4968 const unsigned int max_chunk_len = buffersize / width;
4969 const size_t chunk_len = MIN(count, max_chunk_len);
4970
4971 for (size_t i = 0; i < chunk_len; i++, j++) {
4972 Jim_Obj *tmp = Jim_ListGetIndex(interp, argv[3], j);
4973 jim_wide element_wide;
4974 Jim_GetWide(interp, tmp, &element_wide);
4975
4976 const uint64_t v = element_wide;
4977
4978 switch (width) {
4979 case 8:
4980 target_buffer_set_u64(target, &buffer[i * width], v);
4981 break;
4982 case 4:
4983 target_buffer_set_u32(target, &buffer[i * width], v);
4984 break;
4985 case 2:
4986 target_buffer_set_u16(target, &buffer[i * width], v);
4987 break;
4988 case 1:
4989 buffer[i] = v & 0x0ff;
4990 break;
4991 }
4992 }
4993
4994 count -= chunk_len;
4995
4996 int retval;
4997
4998 if (is_phys)
4999 retval = target_write_phys_memory(target, addr, width, chunk_len, buffer);
5000 else
5001 retval = target_write_memory(target, addr, width, chunk_len, buffer);
5002
5003 if (retval != ERROR_OK) {
5004 LOG_ERROR("write_memory: write at " TARGET_ADDR_FMT " with width=%u and count=%zu failed",
5005 addr, width_bits, chunk_len);
5006 Jim_SetResultString(interp, "write_memory: failed to write memory", -1);
5007 e = JIM_ERR;
5008 break;
5009 }
5010
5011 addr += chunk_len * width;
5012 }
5013
5014 free(buffer);
5015
5016 return e;
5017 }
5018
5019 /* FIX? should we propagate errors here rather than printing them
5020 * and continuing?
5021 */
5022 void target_handle_event(struct target *target, enum target_event e)
5023 {
5024 struct target_event_action *teap;
5025 int retval;
5026
5027 for (teap = target->event_action; teap; teap = teap->next) {
5028 if (teap->event == e) {
5029 LOG_DEBUG("target: %s (%s) event: %d (%s) action: %s",
5030 target_name(target),
5031 target_type_name(target),
5032 e,
5033 target_event_name(e),
5034 Jim_GetString(teap->body, NULL));
5035
5036 /* Override current target by the target an event
5037 * is issued from (lot of scripts need it).
5038 * Return back to previous override as soon
5039 * as the handler processing is done */
5040 struct command_context *cmd_ctx = current_command_context(teap->interp);
5041 struct target *saved_target_override = cmd_ctx->current_target_override;
5042 cmd_ctx->current_target_override = target;
5043
5044 retval = Jim_EvalObj(teap->interp, teap->body);
5045
5046 cmd_ctx->current_target_override = saved_target_override;
5047
5048 if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
5049 return;
5050
5051 if (retval == JIM_RETURN)
5052 retval = teap->interp->returnCode;
5053
5054 if (retval != JIM_OK) {
5055 Jim_MakeErrorMessage(teap->interp);
5056 LOG_USER("Error executing event %s on target %s:\n%s",
5057 target_event_name(e),
5058 target_name(target),
5059 Jim_GetString(Jim_GetResult(teap->interp), NULL));
5060 /* clean both error code and stacktrace before return */
5061 Jim_Eval(teap->interp, "error \"\" \"\"");
5062 }
5063 }
5064 }
5065 }
5066
5067 static int target_jim_get_reg(Jim_Interp *interp, int argc,
5068 Jim_Obj * const *argv)
5069 {
5070 bool force = false;
5071
5072 if (argc == 3) {
5073 const char *option = Jim_GetString(argv[1], NULL);
5074
5075 if (!strcmp(option, "-force")) {
5076 argc--;
5077 argv++;
5078 force = true;
5079 } else {
5080 Jim_SetResultFormatted(interp, "invalid option '%s'", option);
5081 return JIM_ERR;
5082 }
5083 }
5084
5085 if (argc != 2) {
5086 Jim_WrongNumArgs(interp, 1, argv, "[-force] list");
5087 return JIM_ERR;
5088 }
5089
5090 const int length = Jim_ListLength(interp, argv[1]);
5091
5092 Jim_Obj *result_dict = Jim_NewDictObj(interp, NULL, 0);
5093
5094 if (!result_dict)
5095 return JIM_ERR;
5096
5097 struct command_context *cmd_ctx = current_command_context(interp);
5098 assert(cmd_ctx != NULL);
5099 const struct target *target = get_current_target(cmd_ctx);
5100
5101 for (int i = 0; i < length; i++) {
5102 Jim_Obj *elem = Jim_ListGetIndex(interp, argv[1], i);
5103
5104 if (!elem)
5105 return JIM_ERR;
5106
5107 const char *reg_name = Jim_String(elem);
5108
5109 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
5110 false);
5111
5112 if (!reg || !reg->exist) {
5113 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
5114 return JIM_ERR;
5115 }
5116
5117 if (force || !reg->valid) {
5118 int retval = reg->type->get(reg);
5119
5120 if (retval != ERROR_OK) {
5121 Jim_SetResultFormatted(interp, "failed to read register '%s'",
5122 reg_name);
5123 return JIM_ERR;
5124 }
5125 }
5126
5127 char *reg_value = buf_to_hex_str(reg->value, reg->size);
5128
5129 if (!reg_value) {
5130 LOG_ERROR("Failed to allocate memory");
5131 return JIM_ERR;
5132 }
5133
5134 char *tmp = alloc_printf("0x%s", reg_value);
5135
5136 free(reg_value);
5137
5138 if (!tmp) {
5139 LOG_ERROR("Failed to allocate memory");
5140 return JIM_ERR;
5141 }
5142
5143 Jim_DictAddElement(interp, result_dict, elem,
5144 Jim_NewStringObj(interp, tmp, -1));
5145
5146 free(tmp);
5147 }
5148
5149 Jim_SetResult(interp, result_dict);
5150
5151 return JIM_OK;
5152 }
5153
5154 static int target_jim_set_reg(Jim_Interp *interp, int argc,
5155 Jim_Obj * const *argv)
5156 {
5157 if (argc != 2) {
5158 Jim_WrongNumArgs(interp, 1, argv, "dict");
5159 return JIM_ERR;
5160 }
5161
5162 int tmp;
5163 #if JIM_VERSION >= 80
5164 Jim_Obj **dict = Jim_DictPairs(interp, argv[1], &tmp);
5165
5166 if (!dict)
5167 return JIM_ERR;
5168 #else
5169 Jim_Obj **dict;
5170 int ret = Jim_DictPairs(interp, argv[1], &dict, &tmp);
5171
5172 if (ret != JIM_OK)
5173 return ret;
5174 #endif
5175
5176 const unsigned int length = tmp;
5177 struct command_context *cmd_ctx = current_command_context(interp);
5178 assert(cmd_ctx);
5179 const struct target *target = get_current_target(cmd_ctx);
5180
5181 for (unsigned int i = 0; i < length; i += 2) {
5182 const char *reg_name = Jim_String(dict[i]);
5183 const char *reg_value = Jim_String(dict[i + 1]);
5184 struct reg *reg = register_get_by_name(target->reg_cache, reg_name,
5185 false);
5186
5187 if (!reg || !reg->exist) {
5188 Jim_SetResultFormatted(interp, "unknown register '%s'", reg_name);
5189 return JIM_ERR;
5190 }
5191
5192 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
5193
5194 if (!buf) {
5195 LOG_ERROR("Failed to allocate memory");
5196 return JIM_ERR;
5197 }
5198
5199 str_to_buf(reg_value, strlen(reg_value), buf, reg->size, 0);
5200 int retval = reg->type->set(reg, buf);
5201 free(buf);
5202
5203 if (retval != ERROR_OK) {
5204 Jim_SetResultFormatted(interp, "failed to set '%s' to register '%s'",
5205 reg_value, reg_name);
5206 return JIM_ERR;
5207 }
5208 }
5209
5210 return JIM_OK;
5211 }
5212
5213 /**
5214 * Returns true only if the target has a handler for the specified event.
5215 */
5216 bool target_has_event_action(struct target *target, enum target_event event)
5217 {
5218 struct target_event_action *teap;
5219
5220 for (teap = target->event_action; teap; teap = teap->next) {
5221 if (teap->event == event)
5222 return true;
5223 }
5224 return false;
5225 }
5226
5227 enum target_cfg_param {
5228 TCFG_TYPE,
5229 TCFG_EVENT,
5230 TCFG_WORK_AREA_VIRT,
5231 TCFG_WORK_AREA_PHYS,
5232 TCFG_WORK_AREA_SIZE,
5233 TCFG_WORK_AREA_BACKUP,
5234 TCFG_ENDIAN,
5235 TCFG_COREID,
5236 TCFG_CHAIN_POSITION,
5237 TCFG_DBGBASE,
5238 TCFG_RTOS,
5239 TCFG_DEFER_EXAMINE,
5240 TCFG_GDB_PORT,
5241 TCFG_GDB_MAX_CONNECTIONS,
5242 };
5243
5244 static struct jim_nvp nvp_config_opts[] = {
5245 { .name = "-type", .value = TCFG_TYPE },
5246 { .name = "-event", .value = TCFG_EVENT },
5247 { .name = "-work-area-virt", .value = TCFG_WORK_AREA_VIRT },
5248 { .name = "-work-area-phys", .value = TCFG_WORK_AREA_PHYS },
5249 { .name = "-work-area-size", .value = TCFG_WORK_AREA_SIZE },
5250 { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
5251 { .name = "-endian", .value = TCFG_ENDIAN },
5252 { .name = "-coreid", .value = TCFG_COREID },
5253 { .name = "-chain-position", .value = TCFG_CHAIN_POSITION },
5254 { .name = "-dbgbase", .value = TCFG_DBGBASE },
5255 { .name = "-rtos", .value = TCFG_RTOS },
5256 { .name = "-defer-examine", .value = TCFG_DEFER_EXAMINE },
5257 { .name = "-gdb-port", .value = TCFG_GDB_PORT },
5258 { .name = "-gdb-max-connections", .value = TCFG_GDB_MAX_CONNECTIONS },
5259 { .name = NULL, .value = -1 }
5260 };
5261
5262 static int target_configure(struct jim_getopt_info *goi, struct target *target)
5263 {
5264 struct jim_nvp *n;
5265 Jim_Obj *o;
5266 jim_wide w;
5267 int e;
5268
5269 /* parse config or cget options ... */
5270 while (goi->argc > 0) {
5271 Jim_SetEmptyResult(goi->interp);
5272 /* jim_getopt_debug(goi); */
5273
5274 if (target->type->target_jim_configure) {
5275 /* target defines a configure function */
5276 /* target gets first dibs on parameters */
5277 e = (*(target->type->target_jim_configure))(target, goi);
5278 if (e == JIM_OK) {
5279 /* more? */
5280 continue;
5281 }
5282 if (e == JIM_ERR) {
5283 /* An error */
5284 return e;
5285 }
5286 /* otherwise we 'continue' below */
5287 }
5288 e = jim_getopt_nvp(goi, nvp_config_opts, &n);
5289 if (e != JIM_OK) {
5290 jim_getopt_nvp_unknown(goi, nvp_config_opts, 0);
5291 return e;
5292 }
5293 switch (n->value) {
5294 case TCFG_TYPE:
5295 /* not settable */
5296 if (goi->isconfigure) {
5297 Jim_SetResultFormatted(goi->interp,
5298 "not settable: %s", n->name);
5299 return JIM_ERR;
5300 } else {
5301 no_params:
5302 if (goi->argc != 0) {
5303 Jim_WrongNumArgs(goi->interp,
5304 goi->argc, goi->argv,
5305 "NO PARAMS");
5306 return JIM_ERR;
5307 }
5308 }
5309 Jim_SetResultString(goi->interp,
5310 target_type_name(target), -1);
5311 /* loop for more */
5312 break;
5313 case TCFG_EVENT:
5314 if (goi->argc == 0) {
5315 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
5316 return JIM_ERR;
5317 }
5318
5319 e = jim_getopt_nvp(goi, nvp_target_event, &n);
5320 if (e != JIM_OK) {
5321 jim_getopt_nvp_unknown(goi, nvp_target_event, 1);
5322 return e;
5323 }
5324
5325 if (goi->isconfigure) {
5326 if (goi->argc != 1) {
5327 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
5328 return JIM_ERR;
5329 }
5330 } else {
5331 if (goi->argc != 0) {
5332 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
5333 return JIM_ERR;
5334 }
5335 }
5336
5337 {
5338 struct target_event_action *teap;
5339
5340 teap = target->event_action;
5341 /* replace existing? */
5342 while (teap) {
5343 if (teap->event == (enum target_event)n->value)
5344 break;
5345 teap = teap->next;
5346 }
5347
5348 if (goi->isconfigure) {
5349 /* START_DEPRECATED_TPIU */
5350 if (n->value == TARGET_EVENT_TRACE_CONFIG)
5351 LOG_INFO("DEPRECATED target event %s; use TPIU events {pre,post}-{enable,disable}", n->name);
5352 /* END_DEPRECATED_TPIU */
5353
5354 bool replace = true;
5355 if (!teap) {
5356 /* create new */
5357 teap = calloc(1, sizeof(*teap));
5358 replace = false;
5359 }
5360 teap->event = n->value;
5361 teap->interp = goi->interp;
5362 jim_getopt_obj(goi, &o);
5363 if (teap->body)
5364 Jim_DecrRefCount(teap->interp, teap->body);
5365 teap->body = Jim_DuplicateObj(goi->interp, o);
5366 /*
5367 * FIXME:
5368 * Tcl/TK - "tk events" have a nice feature.
5369 * See the "BIND" command.
5370 * We should support that here.
5371 * You can specify %X and %Y in the event code.
5372 * The idea is: %T - target name.
5373 * The idea is: %N - target number
5374 * The idea is: %E - event name.
5375 */
5376 Jim_IncrRefCount(teap->body);
5377
5378 if (!replace) {
5379 /* add to head of event list */
5380 teap->next = target->event_action;
5381 target->event_action = teap;
5382 }
5383 Jim_SetEmptyResult(goi->interp);
5384 } else {
5385 /* get */
5386 if (!teap)
5387 Jim_SetEmptyResult(goi->interp);
5388 else
5389 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
5390 }
5391 }
5392 /* loop for more */
5393 break;
5394
5395 case TCFG_WORK_AREA_VIRT:
5396 if (goi->isconfigure) {
5397 target_free_all_working_areas(target);
5398 e = jim_getopt_wide(goi, &w);
5399 if (e != JIM_OK)
5400 return e;
5401 target->working_area_virt = w;
5402 target->working_area_virt_spec = true;
5403 } else {
5404 if (goi->argc != 0)
5405 goto no_params;
5406 }
5407 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
5408 /* loop for more */
5409 break;
5410
5411 case TCFG_WORK_AREA_PHYS:
5412 if (goi->isconfigure) {
5413 target_free_all_working_areas(target);
5414 e = jim_getopt_wide(goi, &w);
5415 if (e != JIM_OK)
5416 return e;
5417 target->working_area_phys = w;
5418 target->working_area_phys_spec = true;
5419 } else {
5420 if (goi->argc != 0)
5421 goto no_params;
5422 }
5423 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
5424 /* loop for more */
5425 break;
5426
5427 case TCFG_WORK_AREA_SIZE:
5428 if (goi->isconfigure) {
5429 target_free_all_working_areas(target);
5430 e = jim_getopt_wide(goi, &w);
5431 if (e != JIM_OK)
5432 return e;
5433 target->working_area_size = w;
5434 } else {
5435 if (goi->argc != 0)
5436 goto no_params;
5437 }
5438 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
5439 /* loop for more */
5440 break;
5441
5442 case TCFG_WORK_AREA_BACKUP:
5443 if (goi->isconfigure) {
5444 target_free_all_working_areas(target);
5445 e = jim_getopt_wide(goi, &w);
5446 if (e != JIM_OK)
5447 return e;
5448 /* make this exactly 1 or 0 */
5449 target->backup_working_area = (!!w);
5450 } else {
5451 if (goi->argc != 0)
5452 goto no_params;
5453 }
5454 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
5455 /* loop for more e*/
5456 break;
5457
5458
5459 case TCFG_ENDIAN:
5460 if (goi->isconfigure) {
5461 e = jim_getopt_nvp(goi, nvp_target_endian, &n);
5462 if (e != JIM_OK) {
5463 jim_getopt_nvp_unknown(goi, nvp_target_endian, 1);
5464 return e;
5465 }
5466 target->endianness = n->value;
5467 } else {
5468 if (goi->argc != 0)
5469 goto no_params;
5470 }
5471 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5472 if (!n->name) {
5473 target->endianness = TARGET_LITTLE_ENDIAN;
5474 n = jim_nvp_value2name_simple(nvp_target_endian, target->endianness);
5475 }
5476 Jim_SetResultString(goi->interp, n->name, -1);
5477 /* loop for more */
5478 break;
5479
5480 case TCFG_COREID:
5481 if (goi->isconfigure) {
5482 e = jim_getopt_wide(goi, &w);
5483 if (e != JIM_OK)
5484 return e;
5485 target->coreid = (int32_t)w;
5486 } else {
5487 if (goi->argc != 0)
5488 goto no_params;
5489 }
5490 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
5491 /* loop for more */
5492 break;
5493
5494 case TCFG_CHAIN_POSITION:
5495 if (goi->isconfigure) {
5496 Jim_Obj *o_t;
5497 struct jtag_tap *tap;
5498
5499 if (target->has_dap) {
5500 Jim_SetResultString(goi->interp,
5501 "target requires -dap parameter instead of -chain-position!", -1);
5502 return JIM_ERR;
5503 }
5504
5505 target_free_all_working_areas(target);
5506 e = jim_getopt_obj(goi, &o_t);
5507 if (e != JIM_OK)
5508 return e;
5509 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
5510 if (!tap)
5511 return JIM_ERR;
5512 target->tap = tap;
5513 target->tap_configured = true;
5514 } else {
5515 if (goi->argc != 0)
5516 goto no_params;
5517 }
5518 Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
5519 /* loop for more e*/
5520 break;
5521 case TCFG_DBGBASE:
5522 if (goi->isconfigure) {
5523 e = jim_getopt_wide(goi, &w);
5524 if (e != JIM_OK)
5525 return e;
5526 target->dbgbase = (uint32_t)w;
5527 target->dbgbase_set = true;
5528 } else {
5529 if (goi->argc != 0)
5530 goto no_params;
5531 }
5532 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
5533 /* loop for more */
5534 break;
5535 case TCFG_RTOS:
5536 /* RTOS */
5537 {
5538 int result = rtos_create(goi, target);
5539 if (result != JIM_OK)
5540 return result;
5541 }
5542 /* loop for more */
5543 break;
5544
5545 case TCFG_DEFER_EXAMINE:
5546 /* DEFER_EXAMINE */
5547 target->defer_examine = true;
5548 /* loop for more */
5549 break;
5550
5551 case TCFG_GDB_PORT:
5552 if (goi->isconfigure) {
5553 struct command_context *cmd_ctx = current_command_context(goi->interp);
5554 if (cmd_ctx->mode != COMMAND_CONFIG) {
5555 Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
5556 return JIM_ERR;
5557 }
5558
5559 const char *s;
5560 e = jim_getopt_string(goi, &s, NULL);
5561 if (e != JIM_OK)
5562 return e;
5563 free(target->gdb_port_override);
5564 target->gdb_port_override = strdup(s);
5565 } else {
5566 if (goi->argc != 0)
5567 goto no_params;
5568 }
5569 Jim_SetResultString(goi->interp, target->gdb_port_override ? target->gdb_port_override : "undefined", -1);
5570 /* loop for more */
5571 break;
5572
5573 case TCFG_GDB_MAX_CONNECTIONS:
5574 if (goi->isconfigure) {
5575 struct command_context *cmd_ctx = current_command_context(goi->interp);
5576 if (cmd_ctx->mode != COMMAND_CONFIG) {
5577 Jim_SetResultString(goi->interp, "-gdb-max-connections must be configured before 'init'", -1);
5578 return JIM_ERR;
5579 }
5580
5581 e = jim_getopt_wide(goi, &w);
5582 if (e != JIM_OK)
5583 return e;
5584 target->gdb_max_connections = (w < 0) ? CONNECTION_LIMIT_UNLIMITED : (int)w;
5585 } else {
5586 if (goi->argc != 0)
5587 goto no_params;
5588 }
5589 Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->gdb_max_connections));
5590 break;
5591 }
5592 } /* while (goi->argc) */
5593
5594
5595 /* done - we return */
5596 return JIM_OK;
5597 }
5598
5599 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5600 {
5601 struct command *c = jim_to_command(interp);
5602 struct jim_getopt_info goi;
5603
5604 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5605 goi.isconfigure = !strcmp(c->name, "configure");
5606 if (goi.argc < 1) {
5607 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5608 "missing: -option ...");
5609 return JIM_ERR;
5610 }
5611 struct command_context *cmd_ctx = current_command_context(interp);
5612 assert(cmd_ctx);
5613 struct target *target = get_current_target(cmd_ctx);
5614 return target_configure(&goi, target);
5615 }
5616
5617 static int jim_target_mem2array(Jim_Interp *interp,
5618 int argc, Jim_Obj *const *argv)
5619 {
5620 struct command_context *cmd_ctx = current_command_context(interp);
5621 assert(cmd_ctx);
5622 struct target *target = get_current_target(cmd_ctx);
5623 return target_mem2array(interp, target, argc - 1, argv + 1);
5624 }
5625
5626 static int jim_target_array2mem(Jim_Interp *interp,
5627 int argc, Jim_Obj *const *argv)
5628 {
5629 struct command_context *cmd_ctx = current_command_context(interp);
5630 assert(cmd_ctx);
5631 struct target *target = get_current_target(cmd_ctx);
5632 return target_array2mem(interp, target, argc - 1, argv + 1);
5633 }
5634
5635 COMMAND_HANDLER(handle_target_examine)
5636 {
5637 bool allow_defer = false;
5638
5639 if (CMD_ARGC > 1)
5640 return ERROR_COMMAND_SYNTAX_ERROR;
5641
5642 if (CMD_ARGC == 1) {
5643 if (strcmp(CMD_ARGV[0], "allow-defer"))
5644 return ERROR_COMMAND_ARGUMENT_INVALID;
5645 allow_defer = true;
5646 }
5647
5648 struct target *target = get_current_target(CMD_CTX);
5649 if (!target->tap->enabled) {
5650 command_print(CMD, "[TAP is disabled]");
5651 return ERROR_FAIL;
5652 }
5653
5654 if (allow_defer && target->defer_examine) {
5655 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5656 LOG_INFO("Use arp_examine command to examine it manually!");
5657 return ERROR_OK;
5658 }
5659
5660 int retval = target->type->examine(target);
5661 if (retval != ERROR_OK) {
5662 target_reset_examined(target);
5663 return retval;
5664 }
5665
5666 target_set_examined(target);
5667
5668 return ERROR_OK;
5669 }
5670
5671 COMMAND_HANDLER(handle_target_was_examined)
5672 {
5673 if (CMD_ARGC != 0)
5674 return ERROR_COMMAND_SYNTAX_ERROR;
5675
5676 struct target *target = get_current_target(CMD_CTX);
5677
5678 command_print(CMD, "%d", target_was_examined(target) ? 1 : 0);
5679
5680 return ERROR_OK;
5681 }
5682
5683 COMMAND_HANDLER(handle_target_examine_deferred)
5684 {
5685 if (CMD_ARGC != 0)
5686 return ERROR_COMMAND_SYNTAX_ERROR;
5687
5688 struct target *target = get_current_target(CMD_CTX);
5689
5690 command_print(CMD, "%d", target->defer_examine ? 1 : 0);
5691
5692 return ERROR_OK;
5693 }
5694
5695 COMMAND_HANDLER(handle_target_halt_gdb)
5696 {
5697 if (CMD_ARGC != 0)
5698 return ERROR_COMMAND_SYNTAX_ERROR;
5699
5700 struct target *target = get_current_target(CMD_CTX);
5701
5702 return target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
5703 }
5704
5705 COMMAND_HANDLER(handle_target_poll)
5706 {
5707 if (CMD_ARGC != 0)
5708 return ERROR_COMMAND_SYNTAX_ERROR;
5709
5710 struct target *target = get_current_target(CMD_CTX);
5711 if (!target->tap->enabled) {
5712 command_print(CMD, "[TAP is disabled]");
5713 return ERROR_FAIL;
5714 }
5715
5716 if (!(target_was_examined(target)))
5717 return ERROR_TARGET_NOT_EXAMINED;
5718
5719 return target->type->poll(target);
5720 }
5721
5722 COMMAND_HANDLER(handle_target_reset)
5723 {
5724 if (CMD_ARGC != 2)
5725 return ERROR_COMMAND_SYNTAX_ERROR;
5726
5727 const struct nvp *n = nvp_name2value(nvp_assert, CMD_ARGV[0]);
5728 if (!n->name) {
5729 nvp_unknown_command_print(CMD, nvp_assert, NULL, CMD_ARGV[0]);
5730 return ERROR_COMMAND_ARGUMENT_INVALID;
5731 }
5732
5733 /* the halt or not param */
5734 int a;
5735 COMMAND_PARSE_NUMBER(int, CMD_ARGV[1], a);
5736
5737 struct target *target = get_current_target(CMD_CTX);
5738 if (!target->tap->enabled) {
5739 command_print(CMD, "[TAP is disabled]");
5740 return ERROR_FAIL;
5741 }
5742
5743 if (!target->type->assert_reset || !target->type->deassert_reset) {
5744 command_print(CMD, "No target-specific reset for %s", target_name(target));
5745 return ERROR_FAIL;
5746 }
5747
5748 if (target->defer_examine)
5749 target_reset_examined(target);
5750
5751 /* determine if we should halt or not. */
5752 target->reset_halt = (a != 0);
5753 /* When this happens - all workareas are invalid. */
5754 target_free_all_working_areas_restore(target, 0);
5755
5756 /* do the assert */
5757 if (n->value == NVP_ASSERT)
5758 return target->type->assert_reset(target);
5759 return target->type->deassert_reset(target);
5760 }
5761
5762 COMMAND_HANDLER(handle_target_halt)
5763 {
5764 if (CMD_ARGC != 0)
5765 return ERROR_COMMAND_SYNTAX_ERROR;
5766
5767 struct target *target = get_current_target(CMD_CTX);
5768 if (!target->tap->enabled) {
5769 command_print(CMD, "[TAP is disabled]");
5770 return ERROR_FAIL;
5771 }
5772
5773 return target->type->halt(target);
5774 }
5775
5776 COMMAND_HANDLER(handle_target_wait_state)
5777 {
5778 if (CMD_ARGC != 2)
5779 return ERROR_COMMAND_SYNTAX_ERROR;
5780
5781 const struct nvp *n = nvp_name2value(nvp_target_state, CMD_ARGV[0]);
5782 if (!n->name) {
5783 nvp_unknown_command_print(CMD, nvp_target_state, NULL, CMD_ARGV[0]);
5784 return ERROR_COMMAND_ARGUMENT_INVALID;
5785 }
5786
5787 unsigned int a;
5788 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], a);
5789
5790 struct target *target = get_current_target(CMD_CTX);
5791 if (!target->tap->enabled) {
5792 command_print(CMD, "[TAP is disabled]");
5793 return ERROR_FAIL;
5794 }
5795
5796 int retval = target_wait_state(target, n->value, a);
5797 if (retval != ERROR_OK) {
5798 command_print(CMD,
5799 "target: %s wait %s fails (%d) %s",
5800 target_name(target), n->name,
5801 retval, target_strerror_safe(retval));
5802 return retval;
5803 }
5804 return ERROR_OK;
5805 }
5806 /* List for human, Events defined for this target.
5807 * scripts/programs should use 'name cget -event NAME'
5808 */
5809 COMMAND_HANDLER(handle_target_event_list)
5810 {
5811 struct target *target = get_current_target(CMD_CTX);
5812 struct target_event_action *teap = target->event_action;
5813
5814 command_print(CMD, "Event actions for target %s\n",
5815 target_name(target));
5816 command_print(CMD, "%-25s | Body", "Event");
5817 command_print(CMD, "------------------------- | "
5818 "----------------------------------------");
5819 while (teap) {
5820 command_print(CMD, "%-25s | %s",
5821 target_event_name(teap->event),
5822 Jim_GetString(teap->body, NULL));
5823 teap = teap->next;
5824 }
5825 command_print(CMD, "***END***");
5826 return ERROR_OK;
5827 }
5828
5829 COMMAND_HANDLER(handle_target_current_state)
5830 {
5831 if (CMD_ARGC != 0)
5832 return ERROR_COMMAND_SYNTAX_ERROR;
5833
5834 struct target *target = get_current_target(CMD_CTX);
5835
5836 command_print(CMD, "%s", target_state_name(target));
5837
5838 return ERROR_OK;
5839 }
5840
5841 COMMAND_HANDLER(handle_target_debug_reason)
5842 {
5843 if (CMD_ARGC != 0)
5844 return ERROR_COMMAND_SYNTAX_ERROR;
5845
5846 struct target *target = get_current_target(CMD_CTX);
5847
5848
5849 const char *debug_reason = nvp_value2name(nvp_target_debug_reason,
5850 target->debug_reason)->name;
5851
5852 if (!debug_reason) {
5853 command_print(CMD, "bug: invalid debug reason (%d)",
5854 target->debug_reason);
5855 return ERROR_FAIL;
5856 }
5857
5858 command_print(CMD, "%s", debug_reason);
5859
5860 return ERROR_OK;
5861 }
5862
5863 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5864 {
5865 struct jim_getopt_info goi;
5866 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
5867 if (goi.argc != 1) {
5868 const char *cmd_name = Jim_GetString(argv[0], NULL);
5869 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5870 return JIM_ERR;
5871 }
5872 struct jim_nvp *n;
5873 int e = jim_getopt_nvp(&goi, nvp_target_event, &n);
5874 if (e != JIM_OK) {
5875 jim_getopt_nvp_unknown(&goi, nvp_target_event, 1);
5876 return e;
5877 }
5878 struct command_context *cmd_ctx = current_command_context(interp);
5879 assert(cmd_ctx);
5880 struct target *target = get_current_target(cmd_ctx);
5881 target_handle_event(target, n->value);
5882 return JIM_OK;
5883 }
5884
5885 static const struct command_registration target_instance_command_handlers[] = {
5886 {
5887 .name = "configure",
5888 .mode = COMMAND_ANY,
5889 .jim_handler = jim_target_configure,
5890 .help = "configure a new target for use",
5891 .usage = "[target_attribute ...]",
5892 },
5893 {
5894 .name = "cget",
5895 .mode = COMMAND_ANY,
5896 .jim_handler = jim_target_configure,
5897 .help = "returns the specified target attribute",
5898 .usage = "target_attribute",
5899 },
5900 {
5901 .name = "mwd",
5902 .handler = handle_mw_command,
5903 .mode = COMMAND_EXEC,
5904 .help = "Write 64-bit word(s) to target memory",
5905 .usage = "address data [count]",
5906 },
5907 {
5908 .name = "mww",
5909 .handler = handle_mw_command,
5910 .mode = COMMAND_EXEC,
5911 .help = "Write 32-bit word(s) to target memory",
5912 .usage = "address data [count]",
5913 },
5914 {
5915 .name = "mwh",
5916 .handler = handle_mw_command,
5917 .mode = COMMAND_EXEC,
5918 .help = "Write 16-bit half-word(s) to target memory",
5919 .usage = "address data [count]",
5920 },
5921 {
5922 .name = "mwb",
5923 .handler = handle_mw_command,
5924 .mode = COMMAND_EXEC,
5925 .help = "Write byte(s) to target memory",
5926 .usage = "address data [count]",
5927 },
5928 {
5929 .name = "mdd",
5930 .handler = handle_md_command,
5931 .mode = COMMAND_EXEC,
5932 .help = "Display target memory as 64-bit words",
5933 .usage = "address [count]",
5934 },
5935 {
5936 .name = "mdw",
5937 .handler = handle_md_command,
5938 .mode = COMMAND_EXEC,
5939 .help = "Display target memory as 32-bit words",
5940 .usage = "address [count]",
5941 },
5942 {
5943 .name = "mdh",
5944 .handler = handle_md_command,
5945 .mode = COMMAND_EXEC,
5946 .help = "Display target memory as 16-bit half-words",
5947 .usage = "address [count]",
5948 },
5949 {
5950 .name = "mdb",
5951 .handler = handle_md_command,
5952 .mode = COMMAND_EXEC,
5953 .help = "Display target memory as 8-bit bytes",
5954 .usage = "address [count]",
5955 },
5956 {
5957 .name = "array2mem",
5958 .mode = COMMAND_EXEC,
5959 .jim_handler = jim_target_array2mem,
5960 .help = "Writes Tcl array of 8/16/32 bit numbers "
5961 "to target memory",
5962 .usage = "arrayname bitwidth address count",
5963 },
5964 {
5965 .name = "mem2array",
5966 .mode = COMMAND_EXEC,
5967 .jim_handler = jim_target_mem2array,
5968 .help = "Loads Tcl array of 8/16/32 bit numbers "
5969 "from target memory",
5970 .usage = "arrayname bitwidth address count",
5971 },
5972 {
5973 .name = "get_reg",
5974 .mode = COMMAND_EXEC,
5975 .jim_handler = target_jim_get_reg,
5976 .help = "Get register values from the target",
5977 .usage = "list",
5978 },
5979 {
5980 .name = "set_reg",
5981 .mode = COMMAND_EXEC,
5982 .jim_handler = target_jim_set_reg,
5983 .help = "Set target register values",
5984 .usage = "dict",
5985 },
5986 {
5987 .name = "read_memory",
5988 .mode = COMMAND_EXEC,
5989 .handler = handle_target_read_memory,
5990 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
5991 .usage = "address width count ['phys']",
5992 },
5993 {
5994 .name = "write_memory",
5995 .mode = COMMAND_EXEC,
5996 .jim_handler = target_jim_write_memory,
5997 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
5998 .usage = "address width data ['phys']",
5999 },
6000 {
6001 .name = "eventlist",
6002 .handler = handle_target_event_list,
6003 .mode = COMMAND_EXEC,
6004 .help = "displays a table of events defined for this target",
6005 .usage = "",
6006 },
6007 {
6008 .name = "curstate",
6009 .mode = COMMAND_EXEC,
6010 .handler = handle_target_current_state,
6011 .help = "displays the current state of this target",
6012 .usage = "",
6013 },
6014 {
6015 .name = "debug_reason",
6016 .mode = COMMAND_EXEC,
6017 .handler = handle_target_debug_reason,
6018 .help = "displays the debug reason of this target",
6019 .usage = "",
6020 },
6021 {
6022 .name = "arp_examine",
6023 .mode = COMMAND_EXEC,
6024 .handler = handle_target_examine,
6025 .help = "used internally for reset processing",
6026 .usage = "['allow-defer']",
6027 },
6028 {
6029 .name = "was_examined",
6030 .mode = COMMAND_EXEC,
6031 .handler = handle_target_was_examined,
6032 .help = "used internally for reset processing",
6033 .usage = "",
6034 },
6035 {
6036 .name = "examine_deferred",
6037 .mode = COMMAND_EXEC,
6038 .handler = handle_target_examine_deferred,
6039 .help = "used internally for reset processing",
6040 .usage = "",
6041 },
6042 {
6043 .name = "arp_halt_gdb",
6044 .mode = COMMAND_EXEC,
6045 .handler = handle_target_halt_gdb,
6046 .help = "used internally for reset processing to halt GDB",
6047 .usage = "",
6048 },
6049 {
6050 .name = "arp_poll",
6051 .mode = COMMAND_EXEC,
6052 .handler = handle_target_poll,
6053 .help = "used internally for reset processing",
6054 .usage = "",
6055 },
6056 {
6057 .name = "arp_reset",
6058 .mode = COMMAND_EXEC,
6059 .handler = handle_target_reset,
6060 .help = "used internally for reset processing",
6061 .usage = "'assert'|'deassert' halt",
6062 },
6063 {
6064 .name = "arp_halt",
6065 .mode = COMMAND_EXEC,
6066 .handler = handle_target_halt,
6067 .help = "used internally for reset processing",
6068 .usage = "",
6069 },
6070 {
6071 .name = "arp_waitstate",
6072 .mode = COMMAND_EXEC,
6073 .handler = handle_target_wait_state,
6074 .help = "used internally for reset processing",
6075 .usage = "statename timeoutmsecs",
6076 },
6077 {
6078 .name = "invoke-event",
6079 .mode = COMMAND_EXEC,
6080 .jim_handler = jim_target_invoke_event,
6081 .help = "invoke handler for specified event",
6082 .usage = "event_name",
6083 },
6084 COMMAND_REGISTRATION_DONE
6085 };
6086
6087 static int target_create(struct jim_getopt_info *goi)
6088 {
6089 Jim_Obj *new_cmd;
6090 Jim_Cmd *cmd;
6091 const char *cp;
6092 int e;
6093 int x;
6094 struct target *target;
6095 struct command_context *cmd_ctx;
6096
6097 cmd_ctx = current_command_context(goi->interp);
6098 assert(cmd_ctx);
6099
6100 if (goi->argc < 3) {
6101 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
6102 return JIM_ERR;
6103 }
6104
6105 /* COMMAND */
6106 jim_getopt_obj(goi, &new_cmd);
6107 /* does this command exist? */
6108 cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_NONE);
6109 if (cmd) {
6110 cp = Jim_GetString(new_cmd, NULL);
6111 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
6112 return JIM_ERR;
6113 }
6114
6115 /* TYPE */
6116 e = jim_getopt_string(goi, &cp, NULL);
6117 if (e != JIM_OK)
6118 return e;
6119 struct transport *tr = get_current_transport();
6120 if (tr && tr->override_target) {
6121 e = tr->override_target(&cp);
6122 if (e != ERROR_OK) {
6123 LOG_ERROR("The selected transport doesn't support this target");
6124 return JIM_ERR;
6125 }
6126 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
6127 }
6128 /* now does target type exist */
6129 for (x = 0 ; target_types[x] ; x++) {
6130 if (strcmp(cp, target_types[x]->name) == 0) {
6131 /* found */
6132 break;
6133 }
6134 }
6135 if (!target_types[x]) {
6136 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
6137 for (x = 0 ; target_types[x] ; x++) {
6138 if (target_types[x + 1]) {
6139 Jim_AppendStrings(goi->interp,
6140 Jim_GetResult(goi->interp),
6141 target_types[x]->name,
6142 ", ", NULL);
6143 } else {
6144 Jim_AppendStrings(goi->interp,
6145 Jim_GetResult(goi->interp),
6146 " or ",
6147 target_types[x]->name, NULL);
6148 }
6149 }
6150 return JIM_ERR;
6151 }
6152
6153 /* Create it */
6154 target = calloc(1, sizeof(struct target));
6155 if (!target) {
6156 LOG_ERROR("Out of memory");
6157 return JIM_ERR;
6158 }
6159
6160 /* set empty smp cluster */
6161 target->smp_targets = &empty_smp_targets;
6162
6163 /* allocate memory for each unique target type */
6164 target->type = malloc(sizeof(struct target_type));
6165 if (!target->type) {
6166 LOG_ERROR("Out of memory");
6167 free(target);
6168 return JIM_ERR;
6169 }
6170
6171 memcpy(target->type, target_types[x], sizeof(struct target_type));
6172
6173 /* default to first core, override with -coreid */
6174 target->coreid = 0;
6175
6176 target->working_area = 0x0;
6177 target->working_area_size = 0x0;
6178 target->working_areas = NULL;
6179 target->backup_working_area = 0;
6180
6181 target->state = TARGET_UNKNOWN;
6182 target->debug_reason = DBG_REASON_UNDEFINED;
6183 target->reg_cache = NULL;
6184 target->breakpoints = NULL;
6185 target->watchpoints = NULL;
6186 target->next = NULL;
6187 target->arch_info = NULL;
6188
6189 target->verbose_halt_msg = true;
6190
6191 target->halt_issued = false;
6192
6193 /* initialize trace information */
6194 target->trace_info = calloc(1, sizeof(struct trace));
6195 if (!target->trace_info) {
6196 LOG_ERROR("Out of memory");
6197 free(target->type);
6198 free(target);
6199 return JIM_ERR;
6200 }
6201
6202 target->dbgmsg = NULL;
6203 target->dbg_msg_enabled = 0;
6204
6205 target->endianness = TARGET_ENDIAN_UNKNOWN;
6206
6207 target->rtos = NULL;
6208 target->rtos_auto_detect = false;
6209
6210 target->gdb_port_override = NULL;
6211 target->gdb_max_connections = 1;
6212
6213 /* Do the rest as "configure" options */
6214 goi->isconfigure = 1;
6215 e = target_configure(goi, target);
6216
6217 if (e == JIM_OK) {
6218 if (target->has_dap) {
6219 if (!target->dap_configured) {
6220 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
6221 e = JIM_ERR;
6222 }
6223 } else {
6224 if (!target->tap_configured) {
6225 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
6226 e = JIM_ERR;
6227 }
6228 }
6229 /* tap must be set after target was configured */
6230 if (!target->tap)
6231 e = JIM_ERR;
6232 }
6233
6234 if (e != JIM_OK) {
6235 rtos_destroy(target);
6236 free(target->gdb_port_override);
6237 free(target->trace_info);
6238 free(target->type);
6239 free(target);
6240 return e;
6241 }
6242
6243 if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
6244 /* default endian to little if not specified */
6245 target->endianness = TARGET_LITTLE_ENDIAN;
6246 }
6247
6248 cp = Jim_GetString(new_cmd, NULL);
6249 target->cmd_name = strdup(cp);
6250 if (!target->cmd_name) {
6251 LOG_ERROR("Out of memory");
6252 rtos_destroy(target);
6253 free(target->gdb_port_override);
6254 free(target->trace_info);
6255 free(target->type);
6256 free(target);
6257 return JIM_ERR;
6258 }
6259
6260 if (target->type->target_create) {
6261 e = (*(target->type->target_create))(target, goi->interp);
6262 if (e != ERROR_OK) {
6263 LOG_DEBUG("target_create failed");
6264 free(target->cmd_name);
6265 rtos_destroy(target);
6266 free(target->gdb_port_override);
6267 free(target->trace_info);
6268 free(target->type);
6269 free(target);
6270 return JIM_ERR;
6271 }
6272 }
6273
6274 /* create the target specific commands */
6275 if (target->type->commands) {
6276 e = register_commands(cmd_ctx, NULL, target->type->commands);
6277 if (e != ERROR_OK)
6278 LOG_ERROR("unable to register '%s' commands", cp);
6279 }
6280
6281 /* now - create the new target name command */
6282 const struct command_registration target_subcommands[] = {
6283 {
6284 .chain = target_instance_command_handlers,
6285 },
6286 {
6287 .chain = target->type->commands,
6288 },
6289 COMMAND_REGISTRATION_DONE
6290 };
6291 const struct command_registration target_commands[] = {
6292 {
6293 .name = cp,
6294 .mode = COMMAND_ANY,
6295 .help = "target command group",
6296 .usage = "",
6297 .chain = target_subcommands,
6298 },
6299 COMMAND_REGISTRATION_DONE
6300 };
6301 e = register_commands_override_target(cmd_ctx, NULL, target_commands, target);
6302 if (e != ERROR_OK) {
6303 if (target->type->deinit_target)
6304 target->type->deinit_target(target);
6305 free(target->cmd_name);
6306 rtos_destroy(target);
6307 free(target->gdb_port_override);
6308 free(target->trace_info);
6309 free(target->type);
6310 free(target);
6311 return JIM_ERR;
6312 }
6313
6314 /* append to end of list */
6315 append_to_list_all_targets(target);
6316
6317 cmd_ctx->current_target = target;
6318 return JIM_OK;
6319 }
6320
6321 COMMAND_HANDLER(handle_target_current)
6322 {
6323 if (CMD_ARGC != 0)
6324 return ERROR_COMMAND_SYNTAX_ERROR;
6325
6326 struct target *target = get_current_target_or_null(CMD_CTX);
6327 if (target)
6328 command_print(CMD, "%s", target_name(target));
6329
6330 return ERROR_OK;
6331 }
6332
6333 COMMAND_HANDLER(handle_target_types)
6334 {
6335 if (CMD_ARGC != 0)
6336 return ERROR_COMMAND_SYNTAX_ERROR;
6337
6338 for (unsigned int x = 0; target_types[x]; x++)
6339 command_print(CMD, "%s", target_types[x]->name);
6340
6341 return ERROR_OK;
6342 }
6343
6344 COMMAND_HANDLER(handle_target_names)
6345 {
6346 if (CMD_ARGC != 0)
6347 return ERROR_COMMAND_SYNTAX_ERROR;
6348
6349 struct target *target = all_targets;
6350 while (target) {
6351 command_print(CMD, "%s", target_name(target));
6352 target = target->next;
6353 }
6354
6355 return ERROR_OK;
6356 }
6357
6358 static struct target_list *
6359 __attribute__((warn_unused_result))
6360 create_target_list_node(const char *targetname)
6361 {
6362 struct target *target = get_target(targetname);
6363 LOG_DEBUG("%s ", targetname);
6364 if (!target)
6365 return NULL;
6366
6367 struct target_list *new = malloc(sizeof(struct target_list));
6368 if (!new) {
6369 LOG_ERROR("Out of memory");
6370 return new;
6371 }
6372
6373 new->target = target;
6374 return new;
6375 }
6376
6377 static int get_target_with_common_rtos_type(struct command_invocation *cmd,
6378 struct list_head *lh, struct target **result)
6379 {
6380 struct target *target = NULL;
6381 struct target_list *curr;
6382 foreach_smp_target(curr, lh) {
6383 struct rtos *curr_rtos = curr->target->rtos;
6384 if (curr_rtos) {
6385 if (target && target->rtos && target->rtos->type != curr_rtos->type) {
6386 command_print(cmd, "Different rtos types in members of one smp target!");
6387 return ERROR_FAIL;
6388 }
6389 target = curr->target;
6390 }
6391 }
6392 *result = target;
6393 return ERROR_OK;
6394 }
6395
6396 COMMAND_HANDLER(handle_target_smp)
6397 {
6398 static int smp_group = 1;
6399
6400 if (CMD_ARGC == 0) {
6401 LOG_DEBUG("Empty SMP target");
6402 return ERROR_OK;
6403 }
6404 LOG_DEBUG("%d", CMD_ARGC);
6405 /* CMD_ARGC[0] = target to associate in smp
6406 * CMD_ARGC[1] = target to associate in smp
6407 * CMD_ARGC[2] ...
6408 */
6409
6410 struct list_head *lh = malloc(sizeof(*lh));
6411 if (!lh) {
6412 LOG_ERROR("Out of memory");
6413 return ERROR_FAIL;
6414 }
6415 INIT_LIST_HEAD(lh);
6416
6417 for (unsigned int i = 0; i < CMD_ARGC; i++) {
6418 struct target_list *new = create_target_list_node(CMD_ARGV[i]);
6419 if (new)
6420 list_add_tail(&new->lh, lh);
6421 }
6422 /* now parse the list of cpu and put the target in smp mode*/
6423 struct target_list *curr;
6424 foreach_smp_target(curr, lh) {
6425 struct target *target = curr->target;
6426 target->smp = smp_group;
6427 target->smp_targets = lh;
6428 }
6429 smp_group++;
6430
6431 struct target *rtos_target;
6432 int retval = get_target_with_common_rtos_type(CMD, lh, &rtos_target);
6433 if (retval == ERROR_OK && rtos_target)
6434 retval = rtos_smp_init(rtos_target);
6435
6436 return retval;
6437 }
6438
6439 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
6440 {
6441 struct jim_getopt_info goi;
6442 jim_getopt_setup(&goi, interp, argc - 1, argv + 1);
6443 if (goi.argc < 3) {
6444 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
6445 "<name> <target_type> [<target_options> ...]");
6446 return JIM_ERR;
6447 }
6448 return target_create(&goi);
6449 }
6450
6451 static const struct command_registration target_subcommand_handlers[] = {
6452 {
6453 .name = "init",
6454 .mode = COMMAND_CONFIG,
6455 .handler = handle_target_init_command,
6456 .help = "initialize targets",
6457 .usage = "",
6458 },
6459 {
6460 .name = "create",
6461 .mode = COMMAND_CONFIG,
6462 .jim_handler = jim_target_create,
6463 .usage = "name type '-chain-position' name [options ...]",
6464 .help = "Creates and selects a new target",
6465 },
6466 {
6467 .name = "current",
6468 .mode = COMMAND_ANY,
6469 .handler = handle_target_current,
6470 .help = "Returns the currently selected target",
6471 .usage = "",
6472 },
6473 {
6474 .name = "types",
6475 .mode = COMMAND_ANY,
6476 .handler = handle_target_types,
6477 .help = "Returns the available target types as "
6478 "a list of strings",
6479 .usage = "",
6480 },
6481 {
6482 .name = "names",
6483 .mode = COMMAND_ANY,
6484 .handler = handle_target_names,
6485 .help = "Returns the names of all targets as a list of strings",
6486 .usage = "",
6487 },
6488 {
6489 .name = "smp",
6490 .mode = COMMAND_ANY,
6491 .handler = handle_target_smp,
6492 .usage = "targetname1 targetname2 ...",
6493 .help = "gather several target in a smp list"
6494 },
6495
6496 COMMAND_REGISTRATION_DONE
6497 };
6498
6499 struct fast_load {
6500 target_addr_t address;
6501 uint8_t *data;
6502 int length;
6503
6504 };
6505
6506 static int fastload_num;
6507 static struct fast_load *fastload;
6508
6509 static void free_fastload(void)
6510 {
6511 if (fastload) {
6512 for (int i = 0; i < fastload_num; i++)
6513 free(fastload[i].data);
6514 free(fastload);
6515 fastload = NULL;
6516 }
6517 }
6518
6519 COMMAND_HANDLER(handle_fast_load_image_command)
6520 {
6521 uint8_t *buffer;
6522 size_t buf_cnt;
6523 uint32_t image_size;
6524 target_addr_t min_address = 0;
6525 target_addr_t max_address = -1;
6526
6527 struct image image;
6528
6529 int retval = CALL_COMMAND_HANDLER(parse_load_image_command,
6530 &image, &min_address, &max_address);
6531 if (retval != ERROR_OK)
6532 return retval;
6533
6534 struct duration bench;
6535 duration_start(&bench);
6536
6537 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
6538 if (retval != ERROR_OK)
6539 return retval;
6540
6541 image_size = 0x0;
6542 retval = ERROR_OK;
6543 fastload_num = image.num_sections;
6544 fastload = malloc(sizeof(struct fast_load)*image.num_sections);
6545 if (!fastload) {
6546 command_print(CMD, "out of memory");
6547 image_close(&image);
6548 return ERROR_FAIL;
6549 }
6550 memset(fastload, 0, sizeof(struct fast_load)*image.num_sections);
6551 for (unsigned int i = 0; i < image.num_sections; i++) {
6552 buffer = malloc(image.sections[i].size);
6553 if (!buffer) {
6554 command_print(CMD, "error allocating buffer for section (%d bytes)",
6555 (int)(image.sections[i].size));
6556 retval = ERROR_FAIL;
6557 break;
6558 }
6559
6560 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
6561 if (retval != ERROR_OK) {
6562 free(buffer);
6563 break;
6564 }
6565
6566 uint32_t offset = 0;
6567 uint32_t length = buf_cnt;
6568
6569 /* DANGER!!! beware of unsigned comparison here!!! */
6570
6571 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
6572 (image.sections[i].base_address < max_address)) {
6573 if (image.sections[i].base_address < min_address) {
6574 /* clip addresses below */
6575 offset += min_address-image.sections[i].base_address;
6576 length -= offset;
6577 }
6578
6579 if (image.sections[i].base_address + buf_cnt > max_address)
6580 length -= (image.sections[i].base_address + buf_cnt)-max_address;
6581
6582 fastload[i].address = image.sections[i].base_address + offset;
6583 fastload[i].data = malloc(length);
6584 if (!fastload[i].data) {
6585 free(buffer);
6586 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
6587 length);
6588 retval = ERROR_FAIL;
6589 break;
6590 }
6591 memcpy(fastload[i].data, buffer + offset, length);
6592 fastload[i].length = length;
6593
6594 image_size += length;
6595 command_print(CMD, "%u bytes written at address 0x%8.8x",
6596 (unsigned int)length,
6597 ((unsigned int)(image.sections[i].base_address + offset)));
6598 }
6599
6600 free(buffer);
6601 }
6602
6603 if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
6604 command_print(CMD, "Loaded %" PRIu32 " bytes "
6605 "in %fs (%0.3f KiB/s)", image_size,
6606 duration_elapsed(&bench), duration_kbps(&bench, image_size));
6607
6608 command_print(CMD,
6609 "WARNING: image has not been loaded to target!"
6610 "You can issue a 'fast_load' to finish loading.");
6611 }
6612
6613 image_close(&image);
6614
6615 if (retval != ERROR_OK)
6616 free_fastload();
6617
6618 return retval;
6619 }
6620
6621 COMMAND_HANDLER(handle_fast_load_command)
6622 {
6623 if (CMD_ARGC > 0)
6624 return ERROR_COMMAND_SYNTAX_ERROR;
6625 if (!fastload) {
6626 LOG_ERROR("No image in memory");
6627 return ERROR_FAIL;
6628 }
6629 int i;
6630 int64_t ms = timeval_ms();
6631 int size = 0;
6632 int retval = ERROR_OK;
6633 for (i = 0; i < fastload_num; i++) {
6634 struct target *target = get_current_target(CMD_CTX);
6635 command_print(CMD, "Write to 0x%08x, length 0x%08x",
6636 (unsigned int)(fastload[i].address),
6637 (unsigned int)(fastload[i].length));
6638 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
6639 if (retval != ERROR_OK)
6640 break;
6641 size += fastload[i].length;
6642 }
6643 if (retval == ERROR_OK) {
6644 int64_t after = timeval_ms();
6645 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
6646 }
6647 return retval;
6648 }
6649
6650 static const struct command_registration target_command_handlers[] = {
6651 {
6652 .name = "targets",
6653 .handler = handle_targets_command,
6654 .mode = COMMAND_ANY,
6655 .help = "change current default target (one parameter) "
6656 "or prints table of all targets (no parameters)",
6657 .usage = "[target]",
6658 },
6659 {
6660 .name = "target",
6661 .mode = COMMAND_CONFIG,
6662 .help = "configure target",
6663 .chain = target_subcommand_handlers,
6664 .usage = "",
6665 },
6666 COMMAND_REGISTRATION_DONE
6667 };
6668
6669 int target_register_commands(struct command_context *cmd_ctx)
6670 {
6671 return register_commands(cmd_ctx, NULL, target_command_handlers);
6672 }
6673
6674 static bool target_reset_nag = true;
6675
6676 bool get_target_reset_nag(void)
6677 {
6678 return target_reset_nag;
6679 }
6680
6681 COMMAND_HANDLER(handle_target_reset_nag)
6682 {
6683 return CALL_COMMAND_HANDLER(handle_command_parse_bool,
6684 &target_reset_nag, "Nag after each reset about options to improve "
6685 "performance");
6686 }
6687
6688 COMMAND_HANDLER(handle_ps_command)
6689 {
6690 struct target *target = get_current_target(CMD_CTX);
6691 char *display;
6692 if (target->state != TARGET_HALTED) {
6693 command_print(CMD, "Error: [%s] not halted", target_name(target));
6694 return ERROR_TARGET_NOT_HALTED;
6695 }
6696
6697 if ((target->rtos) && (target->rtos->type)
6698 && (target->rtos->type->ps_command)) {
6699 display = target->rtos->type->ps_command(target);
6700 command_print(CMD, "%s", display);
6701 free(display);
6702 return ERROR_OK;
6703 } else {
6704 LOG_INFO("failed");
6705 return ERROR_TARGET_FAILURE;
6706 }
6707 }
6708
6709 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
6710 {
6711 if (text)
6712 command_print_sameline(cmd, "%s", text);
6713 for (int i = 0; i < size; i++)
6714 command_print_sameline(cmd, " %02x", buf[i]);
6715 command_print(cmd, " ");
6716 }
6717
6718 COMMAND_HANDLER(handle_test_mem_access_command)
6719 {
6720 struct target *target = get_current_target(CMD_CTX);
6721 uint32_t test_size;
6722 int retval = ERROR_OK;
6723
6724 if (target->state != TARGET_HALTED) {
6725 command_print(CMD, "Error: [%s] not halted", target_name(target));
6726 return ERROR_TARGET_NOT_HALTED;
6727 }
6728
6729 if (CMD_ARGC != 1)
6730 return ERROR_COMMAND_SYNTAX_ERROR;
6731
6732 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
6733
6734 /* Test reads */
6735 size_t num_bytes = test_size + 4;
6736
6737 struct working_area *wa = NULL;
6738 retval = target_alloc_working_area(target, num_bytes, &wa);
6739 if (retval != ERROR_OK) {
6740 LOG_ERROR("Not enough working area");
6741 return ERROR_FAIL;
6742 }
6743
6744 uint8_t *test_pattern = malloc(num_bytes);
6745
6746 for (size_t i = 0; i < num_bytes; i++)
6747 test_pattern[i] = rand();
6748
6749 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6750 if (retval != ERROR_OK) {
6751 LOG_ERROR("Test pattern write failed");
6752 goto out;
6753 }
6754
6755 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6756 for (int size = 1; size <= 4; size *= 2) {
6757 for (int offset = 0; offset < 4; offset++) {
6758 uint32_t count = test_size / size;
6759 size_t host_bufsiz = (count + 2) * size + host_offset;
6760 uint8_t *read_ref = malloc(host_bufsiz);
6761 uint8_t *read_buf = malloc(host_bufsiz);
6762
6763 for (size_t i = 0; i < host_bufsiz; i++) {
6764 read_ref[i] = rand();
6765 read_buf[i] = read_ref[i];
6766 }
6767 command_print_sameline(CMD,
6768 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6769 size, offset, host_offset ? "un" : "");
6770
6771 struct duration bench;
6772 duration_start(&bench);
6773
6774 retval = target_read_memory(target, wa->address + offset, size, count,
6775 read_buf + size + host_offset);
6776
6777 duration_measure(&bench);
6778
6779 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6780 command_print(CMD, "Unsupported alignment");
6781 goto next;
6782 } else if (retval != ERROR_OK) {
6783 command_print(CMD, "Memory read failed");
6784 goto next;
6785 }
6786
6787 /* replay on host */
6788 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6789
6790 /* check result */
6791 int result = memcmp(read_ref, read_buf, host_bufsiz);
6792 if (result == 0) {
6793 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6794 duration_elapsed(&bench),
6795 duration_kbps(&bench, count * size));
6796 } else {
6797 command_print(CMD, "Compare failed");
6798 binprint(CMD, "ref:", read_ref, host_bufsiz);
6799 binprint(CMD, "buf:", read_buf, host_bufsiz);
6800 }
6801 next:
6802 free(read_ref);
6803 free(read_buf);
6804 }
6805 }
6806 }
6807
6808 out:
6809 free(test_pattern);
6810
6811 target_free_working_area(target, wa);
6812
6813 /* Test writes */
6814 num_bytes = test_size + 4 + 4 + 4;
6815
6816 retval = target_alloc_working_area(target, num_bytes, &wa);
6817 if (retval != ERROR_OK) {
6818 LOG_ERROR("Not enough working area");
6819 return ERROR_FAIL;
6820 }
6821
6822 test_pattern = malloc(num_bytes);
6823
6824 for (size_t i = 0; i < num_bytes; i++)
6825 test_pattern[i] = rand();
6826
6827 for (int host_offset = 0; host_offset <= 1; host_offset++) {
6828 for (int size = 1; size <= 4; size *= 2) {
6829 for (int offset = 0; offset < 4; offset++) {
6830 uint32_t count = test_size / size;
6831 size_t host_bufsiz = count * size + host_offset;
6832 uint8_t *read_ref = malloc(num_bytes);
6833 uint8_t *read_buf = malloc(num_bytes);
6834 uint8_t *write_buf = malloc(host_bufsiz);
6835
6836 for (size_t i = 0; i < host_bufsiz; i++)
6837 write_buf[i] = rand();
6838 command_print_sameline(CMD,
6839 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6840 size, offset, host_offset ? "un" : "");
6841
6842 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6843 if (retval != ERROR_OK) {
6844 command_print(CMD, "Test pattern write failed");
6845 goto nextw;
6846 }
6847
6848 /* replay on host */
6849 memcpy(read_ref, test_pattern, num_bytes);
6850 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6851
6852 struct duration bench;
6853 duration_start(&bench);
6854
6855 retval = target_write_memory(target, wa->address + size + offset, size, count,
6856 write_buf + host_offset);
6857
6858 duration_measure(&bench);
6859
6860 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6861 command_print(CMD, "Unsupported alignment");
6862 goto nextw;
6863 } else if (retval != ERROR_OK) {
6864 command_print(CMD, "Memory write failed");
6865 goto nextw;
6866 }
6867
6868 /* read back */
6869 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6870 if (retval != ERROR_OK) {
6871 command_print(CMD, "Test pattern write failed");
6872 goto nextw;
6873 }
6874
6875 /* check result */
6876 int result = memcmp(read_ref, read_buf, num_bytes);
6877 if (result == 0) {
6878 command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6879 duration_elapsed(&bench),
6880 duration_kbps(&bench, count * size));
6881 } else {
6882 command_print(CMD, "Compare failed");
6883 binprint(CMD, "ref:", read_ref, num_bytes);
6884 binprint(CMD, "buf:", read_buf, num_bytes);
6885 }
6886 nextw:
6887 free(read_ref);
6888 free(read_buf);
6889 }
6890 }
6891 }
6892
6893 free(test_pattern);
6894
6895 target_free_working_area(target, wa);
6896 return retval;
6897 }
6898
6899 static const struct command_registration target_exec_command_handlers[] = {
6900 {
6901 .name = "fast_load_image",
6902 .handler = handle_fast_load_image_command,
6903 .mode = COMMAND_ANY,
6904 .help = "Load image into server memory for later use by "
6905 "fast_load; primarily for profiling",
6906 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6907 "[min_address [max_length]]",
6908 },
6909 {
6910 .name = "fast_load",
6911 .handler = handle_fast_load_command,
6912 .mode = COMMAND_EXEC,
6913 .help = "loads active fast load image to current target "
6914 "- mainly for profiling purposes",
6915 .usage = "",
6916 },
6917 {
6918 .name = "profile",
6919 .handler = handle_profile_command,
6920 .mode = COMMAND_EXEC,
6921 .usage = "seconds filename [start end]",
6922 .help = "profiling samples the CPU PC",
6923 },
6924 /** @todo don't register virt2phys() unless target supports it */
6925 {
6926 .name = "virt2phys",
6927 .handler = handle_virt2phys_command,
6928 .mode = COMMAND_ANY,
6929 .help = "translate a virtual address into a physical address",
6930 .usage = "virtual_address",
6931 },
6932 {
6933 .name = "reg",
6934 .handler = handle_reg_command,
6935 .mode = COMMAND_EXEC,
6936 .help = "display (reread from target with \"force\") or set a register; "
6937 "with no arguments, displays all registers and their values",
6938 .usage = "[(register_number|register_name) [(value|'force')]]",
6939 },
6940 {
6941 .name = "poll",
6942 .handler = handle_poll_command,
6943 .mode = COMMAND_EXEC,
6944 .help = "poll target state; or reconfigure background polling",
6945 .usage = "['on'|'off']",
6946 },
6947 {
6948 .name = "wait_halt",
6949 .handler = handle_wait_halt_command,
6950 .mode = COMMAND_EXEC,
6951 .help = "wait up to the specified number of milliseconds "
6952 "(default 5000) for a previously requested halt",
6953 .usage = "[milliseconds]",
6954 },
6955 {
6956 .name = "halt",
6957 .handler = handle_halt_command,
6958 .mode = COMMAND_EXEC,
6959 .help = "request target to halt, then wait up to the specified "
6960 "number of milliseconds (default 5000) for it to complete",
6961 .usage = "[milliseconds]",
6962 },
6963 {
6964 .name = "resume",
6965 .handler = handle_resume_command,
6966 .mode = COMMAND_EXEC,
6967 .help = "resume target execution from current PC or address",
6968 .usage = "[address]",
6969 },
6970 {
6971 .name = "reset",
6972 .handler = handle_reset_command,
6973 .mode = COMMAND_EXEC,
6974 .usage = "[run|halt|init]",
6975 .help = "Reset all targets into the specified mode. "
6976 "Default reset mode is run, if not given.",
6977 },
6978 {
6979 .name = "soft_reset_halt",
6980 .handler = handle_soft_reset_halt_command,
6981 .mode = COMMAND_EXEC,
6982 .usage = "",
6983 .help = "halt the target and do a soft reset",
6984 },
6985 {
6986 .name = "step",
6987 .handler = handle_step_command,
6988 .mode = COMMAND_EXEC,
6989 .help = "step one instruction from current PC or address",
6990 .usage = "[address]",
6991 },
6992 {
6993 .name = "mdd",
6994 .handler = handle_md_command,
6995 .mode = COMMAND_EXEC,
6996 .help = "display memory double-words",
6997 .usage = "['phys'] address [count]",
6998 },
6999 {
7000 .name = "mdw",
7001 .handler = handle_md_command,
7002 .mode = COMMAND_EXEC,
7003 .help = "display memory words",
7004 .usage = "['phys'] address [count]",
7005 },
7006 {
7007 .name = "mdh",
7008 .handler = handle_md_command,
7009 .mode = COMMAND_EXEC,
7010 .help = "display memory half-words",
7011 .usage = "['phys'] address [count]",
7012 },
7013 {
7014 .name = "mdb",
7015 .handler = handle_md_command,
7016 .mode = COMMAND_EXEC,
7017 .help = "display memory bytes",
7018 .usage = "['phys'] address [count]",
7019 },
7020 {
7021 .name = "mwd",
7022 .handler = handle_mw_command,
7023 .mode = COMMAND_EXEC,
7024 .help = "write memory double-word",
7025 .usage = "['phys'] address value [count]",
7026 },
7027 {
7028 .name = "mww",
7029 .handler = handle_mw_command,
7030 .mode = COMMAND_EXEC,
7031 .help = "write memory word",
7032 .usage = "['phys'] address value [count]",
7033 },
7034 {
7035 .name = "mwh",
7036 .handler = handle_mw_command,
7037 .mode = COMMAND_EXEC,
7038 .help = "write memory half-word",
7039 .usage = "['phys'] address value [count]",
7040 },
7041 {
7042 .name = "mwb",
7043 .handler = handle_mw_command,
7044 .mode = COMMAND_EXEC,
7045 .help = "write memory byte",
7046 .usage = "['phys'] address value [count]",
7047 },
7048 {
7049 .name = "bp",
7050 .handler = handle_bp_command,
7051 .mode = COMMAND_EXEC,
7052 .help = "list or set hardware or software breakpoint",
7053 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
7054 },
7055 {
7056 .name = "rbp",
7057 .handler = handle_rbp_command,
7058 .mode = COMMAND_EXEC,
7059 .help = "remove breakpoint",
7060 .usage = "'all' | address",
7061 },
7062 {
7063 .name = "wp",
7064 .handler = handle_wp_command,
7065 .mode = COMMAND_EXEC,
7066 .help = "list (no params) or create watchpoints",
7067 .usage = "[address length [('r'|'w'|'a') [value [mask]]]]",
7068 },
7069 {
7070 .name = "rwp",
7071 .handler = handle_rwp_command,
7072 .mode = COMMAND_EXEC,
7073 .help = "remove watchpoint",
7074 .usage = "'all' | address",
7075 },
7076 {
7077 .name = "load_image",
7078 .handler = handle_load_image_command,
7079 .mode = COMMAND_EXEC,
7080 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
7081 "[min_address] [max_length]",
7082 },
7083 {
7084 .name = "dump_image",
7085 .handler = handle_dump_image_command,
7086 .mode = COMMAND_EXEC,
7087 .usage = "filename address size",
7088 },
7089 {
7090 .name = "verify_image_checksum",
7091 .handler = handle_verify_image_checksum_command,
7092 .mode = COMMAND_EXEC,
7093 .usage = "filename [offset [type]]",
7094 },
7095 {
7096 .name = "verify_image",
7097 .handler = handle_verify_image_command,
7098 .mode = COMMAND_EXEC,
7099 .usage = "filename [offset [type]]",
7100 },
7101 {
7102 .name = "test_image",
7103 .handler = handle_test_image_command,
7104 .mode = COMMAND_EXEC,
7105 .usage = "filename [offset [type]]",
7106 },
7107 {
7108 .name = "get_reg",
7109 .mode = COMMAND_EXEC,
7110 .jim_handler = target_jim_get_reg,
7111 .help = "Get register values from the target",
7112 .usage = "list",
7113 },
7114 {
7115 .name = "set_reg",
7116 .mode = COMMAND_EXEC,
7117 .jim_handler = target_jim_set_reg,
7118 .help = "Set target register values",
7119 .usage = "dict",
7120 },
7121 {
7122 .name = "read_memory",
7123 .mode = COMMAND_EXEC,
7124 .handler = handle_target_read_memory,
7125 .help = "Read Tcl list of 8/16/32/64 bit numbers from target memory",
7126 .usage = "address width count ['phys']",
7127 },
7128 {
7129 .name = "write_memory",
7130 .mode = COMMAND_EXEC,
7131 .jim_handler = target_jim_write_memory,
7132 .help = "Write Tcl list of 8/16/32/64 bit numbers to target memory",
7133 .usage = "address width data ['phys']",
7134 },
7135 {
7136 .name = "reset_nag",
7137 .handler = handle_target_reset_nag,
7138 .mode = COMMAND_ANY,
7139 .help = "Nag after each reset about options that could have been "
7140 "enabled to improve performance.",
7141 .usage = "['enable'|'disable']",
7142 },
7143 {
7144 .name = "ps",
7145 .handler = handle_ps_command,
7146 .mode = COMMAND_EXEC,
7147 .help = "list all tasks",
7148 .usage = "",
7149 },
7150 {
7151 .name = "test_mem_access",
7152 .handler = handle_test_mem_access_command,
7153 .mode = COMMAND_EXEC,
7154 .help = "Test the target's memory access functions",
7155 .usage = "size",
7156 },
7157
7158 COMMAND_REGISTRATION_DONE
7159 };
7160 static int target_register_user_commands(struct command_context *cmd_ctx)
7161 {
7162 int retval = ERROR_OK;
7163 retval = target_request_register_commands(cmd_ctx);
7164 if (retval != ERROR_OK)
7165 return retval;
7166
7167 retval = trace_register_commands(cmd_ctx);
7168 if (retval != ERROR_OK)
7169 return retval;
7170
7171
7172 return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
7173 }
7174
7175 const char *target_debug_reason_str(enum target_debug_reason reason)
7176 {
7177 switch (reason) {
7178 case DBG_REASON_DBGRQ:
7179 return "DBGRQ";
7180 case DBG_REASON_BREAKPOINT:
7181 return "BREAKPOINT";
7182 case DBG_REASON_WATCHPOINT:
7183 return "WATCHPOINT";
7184 case DBG_REASON_WPTANDBKPT:
7185 return "WPTANDBKPT";
7186 case DBG_REASON_SINGLESTEP:
7187 return "SINGLESTEP";
7188 case DBG_REASON_NOTHALTED:
7189 return "NOTHALTED";
7190 case DBG_REASON_EXIT:
7191 return "EXIT";
7192 case DBG_REASON_EXC_CATCH:
7193 return "EXC_CATCH";
7194 case DBG_REASON_UNDEFINED:
7195 return "UNDEFINED";
7196 default:
7197 return "UNKNOWN!";
7198 }
7199 }

Linking to existing account procedure

If you already have an account and want to add another login method you MUST first sign in with your existing account and then change URL to read https://review.openocd.org/login/?link to get to this page again but this time it'll work for linking. Thank you.

SSH host keys fingerprints

1024 SHA256:YKx8b7u5ZWdcbp7/4AeXNaqElP49m6QrwfXaqQGJAOk gerrit-code-review@openocd.zylin.com (DSA)
384 SHA256:jHIbSQa4REvwCFG4cq5LBlBLxmxSqelQPem/EXIrxjk gerrit-code-review@openocd.org (ECDSA)
521 SHA256:UAOPYkU9Fjtcao0Ul/Rrlnj/OsQvt+pgdYSZ4jOYdgs gerrit-code-review@openocd.org (ECDSA)
256 SHA256:A13M5QlnozFOvTllybRZH6vm7iSt0XLxbA48yfc2yfY gerrit-code-review@openocd.org (ECDSA)
256 SHA256:spYMBqEYoAOtK7yZBrcwE8ZpYt6b68Cfh9yEVetvbXg gerrit-code-review@openocd.org (ED25519)
+--[ED25519 256]--+
|=..              |
|+o..   .         |
|*.o   . .        |
|+B . . .         |
|Bo. = o S        |
|Oo.+ + =         |
|oB=.* = . o      |
| =+=.+   + E     |
|. .=o   . o      |
+----[SHA256]-----+
2048 SHA256:0Onrb7/PHjpo6iVZ7xQX2riKN83FJ3KGU0TvI0TaFG4 gerrit-code-review@openocd.zylin.com (RSA)