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

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)