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

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)