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

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)