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

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)