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

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)