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

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)