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

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)