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

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)