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

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)