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

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)