51fdff3425e0e630084690fefa1f234b9d3ccbc7
[openocd.git] / src / target / target.c
1 /***************************************************************************
2 * Copyright (C) 2005 by Dominic Rath *
3 * Dominic.Rath@gmx.de *
4 * *
5 * Copyright (C) 2007-2010 √ėyvind Harboe *
6 * oyvind.harboe@zylin.com *
7 * *
8 * Copyright (C) 2008, Duane Ellis *
9 * openocd@duaneeellis.com *
10 * *
11 * Copyright (C) 2008 by Spencer Oliver *
12 * spen@spen-soft.co.uk *
13 * *
14 * Copyright (C) 2008 by Rick Altherr *
15 * kc8apf@kc8apf.net> *
16 * *
17 * Copyright (C) 2011 by Broadcom Corporation *
18 * Evan Hunter - ehunter@broadcom.com *
19 * *
20 * Copyright (C) ST-Ericsson SA 2011 *
21 * michel.jaouen@stericsson.com : smp minimum support *
22 * *
23 * Copyright (C) 2011 Andreas Fritiofson *
24 * andreas.fritiofson@gmail.com *
25 * *
26 * This program is free software; you can redistribute it and/or modify *
27 * it under the terms of the GNU General Public License as published by *
28 * the Free Software Foundation; either version 2 of the License, or *
29 * (at your option) any later version. *
30 * *
31 * This program is distributed in the hope that it will be useful, *
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
34 * GNU General Public License for more details. *
35 * *
36 * You should have received a copy of the GNU General Public License *
37 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
38 ***************************************************************************/
39
40 #ifdef HAVE_CONFIG_H
41 #include "config.h"
42 #endif
43
44 #include <helper/time_support.h>
45 #include <jtag/jtag.h>
46 #include <flash/nor/core.h>
47
48 #include "target.h"
49 #include "target_type.h"
50 #include "target_request.h"
51 #include "breakpoints.h"
52 #include "register.h"
53 #include "trace.h"
54 #include "image.h"
55 #include "rtos/rtos.h"
56 #include "transport/transport.h"
57 #include "arm_cti.h"
58
59 /* default halt wait timeout (ms) */
60 #define DEFAULT_HALT_TIMEOUT 5000
61
62 static int target_read_buffer_default(struct target *target, target_addr_t address,
63 uint32_t count, uint8_t *buffer);
64 static int target_write_buffer_default(struct target *target, target_addr_t address,
65 uint32_t count, const uint8_t *buffer);
66 static int target_array2mem(Jim_Interp *interp, struct target *target,
67 int argc, Jim_Obj * const *argv);
68 static int target_mem2array(Jim_Interp *interp, struct target *target,
69 int argc, Jim_Obj * const *argv);
70 static int target_register_user_commands(struct command_context *cmd_ctx);
71 static int target_get_gdb_fileio_info_default(struct target *target,
72 struct gdb_fileio_info *fileio_info);
73 static int target_gdb_fileio_end_default(struct target *target, int retcode,
74 int fileio_errno, bool ctrl_c);
75 static int target_profiling_default(struct target *target, uint32_t *samples,
76 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds);
77
78 /* targets */
79 extern struct target_type arm7tdmi_target;
80 extern struct target_type arm720t_target;
81 extern struct target_type arm9tdmi_target;
82 extern struct target_type arm920t_target;
83 extern struct target_type arm966e_target;
84 extern struct target_type arm946e_target;
85 extern struct target_type arm926ejs_target;
86 extern struct target_type fa526_target;
87 extern struct target_type feroceon_target;
88 extern struct target_type dragonite_target;
89 extern struct target_type xscale_target;
90 extern struct target_type cortexm_target;
91 extern struct target_type cortexa_target;
92 extern struct target_type aarch64_target;
93 extern struct target_type cortexr4_target;
94 extern struct target_type arm11_target;
95 extern struct target_type ls1_sap_target;
96 extern struct target_type mips_m4k_target;
97 extern struct target_type avr_target;
98 extern struct target_type dsp563xx_target;
99 extern struct target_type dsp5680xx_target;
100 extern struct target_type testee_target;
101 extern struct target_type avr32_ap7k_target;
102 extern struct target_type hla_target;
103 extern struct target_type nds32_v2_target;
104 extern struct target_type nds32_v3_target;
105 extern struct target_type nds32_v3m_target;
106 extern struct target_type or1k_target;
107 extern struct target_type quark_x10xx_target;
108 extern struct target_type quark_d20xx_target;
109 extern struct target_type stm8_target;
110 extern struct target_type riscv_target;
111 extern struct target_type mem_ap_target;
112 extern struct target_type esirisc_target;
113
114 static struct target_type *target_types[] = {
115 &arm7tdmi_target,
116 &arm9tdmi_target,
117 &arm920t_target,
118 &arm720t_target,
119 &arm966e_target,
120 &arm946e_target,
121 &arm926ejs_target,
122 &fa526_target,
123 &feroceon_target,
124 &dragonite_target,
125 &xscale_target,
126 &cortexm_target,
127 &cortexa_target,
128 &cortexr4_target,
129 &arm11_target,
130 &ls1_sap_target,
131 &mips_m4k_target,
132 &avr_target,
133 &dsp563xx_target,
134 &dsp5680xx_target,
135 &testee_target,
136 &avr32_ap7k_target,
137 &hla_target,
138 &nds32_v2_target,
139 &nds32_v3_target,
140 &nds32_v3m_target,
141 &or1k_target,
142 &quark_x10xx_target,
143 &quark_d20xx_target,
144 &stm8_target,
145 &riscv_target,
146 &mem_ap_target,
147 &esirisc_target,
148 #if BUILD_TARGET64
149 &aarch64_target,
150 #endif
151 NULL,
152 };
153
154 struct target *all_targets;
155 static struct target_event_callback *target_event_callbacks;
156 static struct target_timer_callback *target_timer_callbacks;
157 LIST_HEAD(target_reset_callback_list);
158 LIST_HEAD(target_trace_callback_list);
159 static const int polling_interval = 100;
160
161 static const Jim_Nvp nvp_assert[] = {
162 { .name = "assert", NVP_ASSERT },
163 { .name = "deassert", NVP_DEASSERT },
164 { .name = "T", NVP_ASSERT },
165 { .name = "F", NVP_DEASSERT },
166 { .name = "t", NVP_ASSERT },
167 { .name = "f", NVP_DEASSERT },
168 { .name = NULL, .value = -1 }
169 };
170
171 static const Jim_Nvp nvp_error_target[] = {
172 { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
173 { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
174 { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
175 { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
176 { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
177 { .value = ERROR_TARGET_UNALIGNED_ACCESS , .name = "err-unaligned-access" },
178 { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
179 { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
180 { .value = ERROR_TARGET_TRANSLATION_FAULT , .name = "err-translation-fault" },
181 { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
182 { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
183 { .value = -1, .name = NULL }
184 };
185
186 static const char *target_strerror_safe(int err)
187 {
188 const Jim_Nvp *n;
189
190 n = Jim_Nvp_value2name_simple(nvp_error_target, err);
191 if (n->name == NULL)
192 return "unknown";
193 else
194 return n->name;
195 }
196
197 static const Jim_Nvp nvp_target_event[] = {
198
199 { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
200 { .value = TARGET_EVENT_HALTED, .name = "halted" },
201 { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
202 { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
203 { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
204
205 { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
206 { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
207
208 { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
209 { .value = TARGET_EVENT_RESET_ASSERT_PRE, .name = "reset-assert-pre" },
210 { .value = TARGET_EVENT_RESET_ASSERT, .name = "reset-assert" },
211 { .value = TARGET_EVENT_RESET_ASSERT_POST, .name = "reset-assert-post" },
212 { .value = TARGET_EVENT_RESET_DEASSERT_PRE, .name = "reset-deassert-pre" },
213 { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
214 { .value = TARGET_EVENT_RESET_INIT, .name = "reset-init" },
215 { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
216
217 { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
218 { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
219
220 { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
221 { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
222
223 { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
224 { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
225
226 { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
227 { .value = TARGET_EVENT_GDB_FLASH_WRITE_END , .name = "gdb-flash-write-end" },
228
229 { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
230 { .value = TARGET_EVENT_GDB_FLASH_ERASE_END , .name = "gdb-flash-erase-end" },
231
232 { .value = TARGET_EVENT_TRACE_CONFIG, .name = "trace-config" },
233
234 { .name = NULL, .value = -1 }
235 };
236
237 static const Jim_Nvp nvp_target_state[] = {
238 { .name = "unknown", .value = TARGET_UNKNOWN },
239 { .name = "running", .value = TARGET_RUNNING },
240 { .name = "halted", .value = TARGET_HALTED },
241 { .name = "reset", .value = TARGET_RESET },
242 { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
243 { .name = NULL, .value = -1 },
244 };
245
246 static const Jim_Nvp nvp_target_debug_reason[] = {
247 { .name = "debug-request" , .value = DBG_REASON_DBGRQ },
248 { .name = "breakpoint" , .value = DBG_REASON_BREAKPOINT },
249 { .name = "watchpoint" , .value = DBG_REASON_WATCHPOINT },
250 { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
251 { .name = "single-step" , .value = DBG_REASON_SINGLESTEP },
252 { .name = "target-not-halted" , .value = DBG_REASON_NOTHALTED },
253 { .name = "program-exit" , .value = DBG_REASON_EXIT },
254 { .name = "exception-catch" , .value = DBG_REASON_EXC_CATCH },
255 { .name = "undefined" , .value = DBG_REASON_UNDEFINED },
256 { .name = NULL, .value = -1 },
257 };
258
259 static const Jim_Nvp nvp_target_endian[] = {
260 { .name = "big", .value = TARGET_BIG_ENDIAN },
261 { .name = "little", .value = TARGET_LITTLE_ENDIAN },
262 { .name = "be", .value = TARGET_BIG_ENDIAN },
263 { .name = "le", .value = TARGET_LITTLE_ENDIAN },
264 { .name = NULL, .value = -1 },
265 };
266
267 static const Jim_Nvp nvp_reset_modes[] = {
268 { .name = "unknown", .value = RESET_UNKNOWN },
269 { .name = "run" , .value = RESET_RUN },
270 { .name = "halt" , .value = RESET_HALT },
271 { .name = "init" , .value = RESET_INIT },
272 { .name = NULL , .value = -1 },
273 };
274
275 const char *debug_reason_name(struct target *t)
276 {
277 const char *cp;
278
279 cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
280 t->debug_reason)->name;
281 if (!cp) {
282 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
283 cp = "(*BUG*unknown*BUG*)";
284 }
285 return cp;
286 }
287
288 const char *target_state_name(struct target *t)
289 {
290 const char *cp;
291 cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
292 if (!cp) {
293 LOG_ERROR("Invalid target state: %d", (int)(t->state));
294 cp = "(*BUG*unknown*BUG*)";
295 }
296
297 if (!target_was_examined(t) && t->defer_examine)
298 cp = "examine deferred";
299
300 return cp;
301 }
302
303 const char *target_event_name(enum target_event event)
304 {
305 const char *cp;
306 cp = Jim_Nvp_value2name_simple(nvp_target_event, event)->name;
307 if (!cp) {
308 LOG_ERROR("Invalid target event: %d", (int)(event));
309 cp = "(*BUG*unknown*BUG*)";
310 }
311 return cp;
312 }
313
314 const char *target_reset_mode_name(enum target_reset_mode reset_mode)
315 {
316 const char *cp;
317 cp = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name;
318 if (!cp) {
319 LOG_ERROR("Invalid target reset mode: %d", (int)(reset_mode));
320 cp = "(*BUG*unknown*BUG*)";
321 }
322 return cp;
323 }
324
325 /* determine the number of the new target */
326 static int new_target_number(void)
327 {
328 struct target *t;
329 int x;
330
331 /* number is 0 based */
332 x = -1;
333 t = all_targets;
334 while (t) {
335 if (x < t->target_number)
336 x = t->target_number;
337 t = t->next;
338 }
339 return x + 1;
340 }
341
342 /* read a uint64_t from a buffer in target memory endianness */
343 uint64_t target_buffer_get_u64(struct target *target, const uint8_t *buffer)
344 {
345 if (target->endianness == TARGET_LITTLE_ENDIAN)
346 return le_to_h_u64(buffer);
347 else
348 return be_to_h_u64(buffer);
349 }
350
351 /* read a uint32_t from a buffer in target memory endianness */
352 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
353 {
354 if (target->endianness == TARGET_LITTLE_ENDIAN)
355 return le_to_h_u32(buffer);
356 else
357 return be_to_h_u32(buffer);
358 }
359
360 /* read a uint24_t from a buffer in target memory endianness */
361 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
362 {
363 if (target->endianness == TARGET_LITTLE_ENDIAN)
364 return le_to_h_u24(buffer);
365 else
366 return be_to_h_u24(buffer);
367 }
368
369 /* read a uint16_t from a buffer in target memory endianness */
370 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
371 {
372 if (target->endianness == TARGET_LITTLE_ENDIAN)
373 return le_to_h_u16(buffer);
374 else
375 return be_to_h_u16(buffer);
376 }
377
378 /* write a uint64_t to a buffer in target memory endianness */
379 void target_buffer_set_u64(struct target *target, uint8_t *buffer, uint64_t value)
380 {
381 if (target->endianness == TARGET_LITTLE_ENDIAN)
382 h_u64_to_le(buffer, value);
383 else
384 h_u64_to_be(buffer, value);
385 }
386
387 /* write a uint32_t to a buffer in target memory endianness */
388 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
389 {
390 if (target->endianness == TARGET_LITTLE_ENDIAN)
391 h_u32_to_le(buffer, value);
392 else
393 h_u32_to_be(buffer, value);
394 }
395
396 /* write a uint24_t to a buffer in target memory endianness */
397 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
398 {
399 if (target->endianness == TARGET_LITTLE_ENDIAN)
400 h_u24_to_le(buffer, value);
401 else
402 h_u24_to_be(buffer, value);
403 }
404
405 /* write a uint16_t to a buffer in target memory endianness */
406 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
407 {
408 if (target->endianness == TARGET_LITTLE_ENDIAN)
409 h_u16_to_le(buffer, value);
410 else
411 h_u16_to_be(buffer, value);
412 }
413
414 /* write a uint8_t to a buffer in target memory endianness */
415 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
416 {
417 *buffer = value;
418 }
419
420 /* write a uint64_t array to a buffer in target memory endianness */
421 void target_buffer_get_u64_array(struct target *target, const uint8_t *buffer, uint32_t count, uint64_t *dstbuf)
422 {
423 uint32_t i;
424 for (i = 0; i < count; i++)
425 dstbuf[i] = target_buffer_get_u64(target, &buffer[i * 8]);
426 }
427
428 /* write a uint32_t array to a buffer in target memory endianness */
429 void target_buffer_get_u32_array(struct target *target, const uint8_t *buffer, uint32_t count, uint32_t *dstbuf)
430 {
431 uint32_t i;
432 for (i = 0; i < count; i++)
433 dstbuf[i] = target_buffer_get_u32(target, &buffer[i * 4]);
434 }
435
436 /* write a uint16_t array to a buffer in target memory endianness */
437 void target_buffer_get_u16_array(struct target *target, const uint8_t *buffer, uint32_t count, uint16_t *dstbuf)
438 {
439 uint32_t i;
440 for (i = 0; i < count; i++)
441 dstbuf[i] = target_buffer_get_u16(target, &buffer[i * 2]);
442 }
443
444 /* write a uint64_t array to a buffer in target memory endianness */
445 void target_buffer_set_u64_array(struct target *target, uint8_t *buffer, uint32_t count, const uint64_t *srcbuf)
446 {
447 uint32_t i;
448 for (i = 0; i < count; i++)
449 target_buffer_set_u64(target, &buffer[i * 8], srcbuf[i]);
450 }
451
452 /* write a uint32_t array to a buffer in target memory endianness */
453 void target_buffer_set_u32_array(struct target *target, uint8_t *buffer, uint32_t count, const uint32_t *srcbuf)
454 {
455 uint32_t i;
456 for (i = 0; i < count; i++)
457 target_buffer_set_u32(target, &buffer[i * 4], srcbuf[i]);
458 }
459
460 /* write a uint16_t array to a buffer in target memory endianness */
461 void target_buffer_set_u16_array(struct target *target, uint8_t *buffer, uint32_t count, const uint16_t *srcbuf)
462 {
463 uint32_t i;
464 for (i = 0; i < count; i++)
465 target_buffer_set_u16(target, &buffer[i * 2], srcbuf[i]);
466 }
467
468 /* return a pointer to a configured target; id is name or number */
469 struct target *get_target(const char *id)
470 {
471 struct target *target;
472
473 /* try as tcltarget name */
474 for (target = all_targets; target; target = target->next) {
475 if (target_name(target) == NULL)
476 continue;
477 if (strcmp(id, target_name(target)) == 0)
478 return target;
479 }
480
481 /* It's OK to remove this fallback sometime after August 2010 or so */
482
483 /* no match, try as number */
484 unsigned num;
485 if (parse_uint(id, &num) != ERROR_OK)
486 return NULL;
487
488 for (target = all_targets; target; target = target->next) {
489 if (target->target_number == (int)num) {
490 LOG_WARNING("use '%s' as target identifier, not '%u'",
491 target_name(target), num);
492 return target;
493 }
494 }
495
496 return NULL;
497 }
498
499 /* returns a pointer to the n-th configured target */
500 struct target *get_target_by_num(int num)
501 {
502 struct target *target = all_targets;
503
504 while (target) {
505 if (target->target_number == num)
506 return target;
507 target = target->next;
508 }
509
510 return NULL;
511 }
512
513 struct target *get_current_target(struct command_context *cmd_ctx)
514 {
515 struct target *target = get_current_target_or_null(cmd_ctx);
516
517 if (target == NULL) {
518 LOG_ERROR("BUG: current_target out of bounds");
519 exit(-1);
520 }
521
522 return target;
523 }
524
525 struct target *get_current_target_or_null(struct command_context *cmd_ctx)
526 {
527 return cmd_ctx->current_target_override
528 ? cmd_ctx->current_target_override
529 : cmd_ctx->current_target;
530 }
531
532 int target_poll(struct target *target)
533 {
534 int retval;
535
536 /* We can't poll until after examine */
537 if (!target_was_examined(target)) {
538 /* Fail silently lest we pollute the log */
539 return ERROR_FAIL;
540 }
541
542 retval = target->type->poll(target);
543 if (retval != ERROR_OK)
544 return retval;
545
546 if (target->halt_issued) {
547 if (target->state == TARGET_HALTED)
548 target->halt_issued = false;
549 else {
550 int64_t t = timeval_ms() - target->halt_issued_time;
551 if (t > DEFAULT_HALT_TIMEOUT) {
552 target->halt_issued = false;
553 LOG_INFO("Halt timed out, wake up GDB.");
554 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
555 }
556 }
557 }
558
559 return ERROR_OK;
560 }
561
562 int target_halt(struct target *target)
563 {
564 int retval;
565 /* We can't poll until after examine */
566 if (!target_was_examined(target)) {
567 LOG_ERROR("Target not examined yet");
568 return ERROR_FAIL;
569 }
570
571 retval = target->type->halt(target);
572 if (retval != ERROR_OK)
573 return retval;
574
575 target->halt_issued = true;
576 target->halt_issued_time = timeval_ms();
577
578 return ERROR_OK;
579 }
580
581 /**
582 * Make the target (re)start executing using its saved execution
583 * context (possibly with some modifications).
584 *
585 * @param target Which target should start executing.
586 * @param current True to use the target's saved program counter instead
587 * of the address parameter
588 * @param address Optionally used as the program counter.
589 * @param handle_breakpoints True iff breakpoints at the resumption PC
590 * should be skipped. (For example, maybe execution was stopped by
591 * such a breakpoint, in which case it would be counterprodutive to
592 * let it re-trigger.
593 * @param debug_execution False if all working areas allocated by OpenOCD
594 * should be released and/or restored to their original contents.
595 * (This would for example be true to run some downloaded "helper"
596 * algorithm code, which resides in one such working buffer and uses
597 * another for data storage.)
598 *
599 * @todo Resolve the ambiguity about what the "debug_execution" flag
600 * signifies. For example, Target implementations don't agree on how
601 * it relates to invalidation of the register cache, or to whether
602 * breakpoints and watchpoints should be enabled. (It would seem wrong
603 * to enable breakpoints when running downloaded "helper" algorithms
604 * (debug_execution true), since the breakpoints would be set to match
605 * target firmware being debugged, not the helper algorithm.... and
606 * enabling them could cause such helpers to malfunction (for example,
607 * by overwriting data with a breakpoint instruction. On the other
608 * hand the infrastructure for running such helpers might use this
609 * procedure but rely on hardware breakpoint to detect termination.)
610 */
611 int target_resume(struct target *target, int current, target_addr_t address,
612 int handle_breakpoints, int debug_execution)
613 {
614 int retval;
615
616 /* We can't poll until after examine */
617 if (!target_was_examined(target)) {
618 LOG_ERROR("Target not examined yet");
619 return ERROR_FAIL;
620 }
621
622 target_call_event_callbacks(target, TARGET_EVENT_RESUME_START);
623
624 /* note that resume *must* be asynchronous. The CPU can halt before
625 * we poll. The CPU can even halt at the current PC as a result of
626 * a software breakpoint being inserted by (a bug?) the application.
627 */
628 retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution);
629 if (retval != ERROR_OK)
630 return retval;
631
632 target_call_event_callbacks(target, TARGET_EVENT_RESUME_END);
633
634 return retval;
635 }
636
637 static int target_process_reset(struct command_invocation *cmd, enum target_reset_mode reset_mode)
638 {
639 char buf[100];
640 int retval;
641 Jim_Nvp *n;
642 n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
643 if (n->name == NULL) {
644 LOG_ERROR("invalid reset mode");
645 return ERROR_FAIL;
646 }
647
648 struct target *target;
649 for (target = all_targets; target; target = target->next)
650 target_call_reset_callbacks(target, reset_mode);
651
652 /* disable polling during reset to make reset event scripts
653 * more predictable, i.e. dr/irscan & pathmove in events will
654 * not have JTAG operations injected into the middle of a sequence.
655 */
656 bool save_poll = jtag_poll_get_enabled();
657
658 jtag_poll_set_enabled(false);
659
660 sprintf(buf, "ocd_process_reset %s", n->name);
661 retval = Jim_Eval(cmd->ctx->interp, buf);
662
663 jtag_poll_set_enabled(save_poll);
664
665 if (retval != JIM_OK) {
666 Jim_MakeErrorMessage(cmd->ctx->interp);
667 command_print(cmd, "%s", Jim_GetString(Jim_GetResult(cmd->ctx->interp), NULL));
668 return ERROR_FAIL;
669 }
670
671 /* We want any events to be processed before the prompt */
672 retval = target_call_timer_callbacks_now();
673
674 for (target = all_targets; target; target = target->next) {
675 target->type->check_reset(target);
676 target->running_alg = false;
677 }
678
679 return retval;
680 }
681
682 static int identity_virt2phys(struct target *target,
683 target_addr_t virtual, target_addr_t *physical)
684 {
685 *physical = virtual;
686 return ERROR_OK;
687 }
688
689 static int no_mmu(struct target *target, int *enabled)
690 {
691 *enabled = 0;
692 return ERROR_OK;
693 }
694
695 static int default_examine(struct target *target)
696 {
697 target_set_examined(target);
698 return ERROR_OK;
699 }
700
701 /* no check by default */
702 static int default_check_reset(struct target *target)
703 {
704 return ERROR_OK;
705 }
706
707 int target_examine_one(struct target *target)
708 {
709 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_START);
710
711 int retval = target->type->examine(target);
712 if (retval != ERROR_OK)
713 return retval;
714
715 target_call_event_callbacks(target, TARGET_EVENT_EXAMINE_END);
716
717 return ERROR_OK;
718 }
719
720 static int jtag_enable_callback(enum jtag_event event, void *priv)
721 {
722 struct target *target = priv;
723
724 if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
725 return ERROR_OK;
726
727 jtag_unregister_event_callback(jtag_enable_callback, target);
728
729 return target_examine_one(target);
730 }
731
732 /* Targets that correctly implement init + examine, i.e.
733 * no communication with target during init:
734 *
735 * XScale
736 */
737 int target_examine(void)
738 {
739 int retval = ERROR_OK;
740 struct target *target;
741
742 for (target = all_targets; target; target = target->next) {
743 /* defer examination, but don't skip it */
744 if (!target->tap->enabled) {
745 jtag_register_event_callback(jtag_enable_callback,
746 target);
747 continue;
748 }
749
750 if (target->defer_examine)
751 continue;
752
753 retval = target_examine_one(target);
754 if (retval != ERROR_OK)
755 return retval;
756 }
757 return retval;
758 }
759
760 const char *target_type_name(struct target *target)
761 {
762 return target->type->name;
763 }
764
765 static int target_soft_reset_halt(struct target *target)
766 {
767 if (!target_was_examined(target)) {
768 LOG_ERROR("Target not examined yet");
769 return ERROR_FAIL;
770 }
771 if (!target->type->soft_reset_halt) {
772 LOG_ERROR("Target %s does not support soft_reset_halt",
773 target_name(target));
774 return ERROR_FAIL;
775 }
776 return target->type->soft_reset_halt(target);
777 }
778
779 /**
780 * Downloads a target-specific native code algorithm to the target,
781 * and executes it. * Note that some targets may need to set up, enable,
782 * and tear down a breakpoint (hard or * soft) to detect algorithm
783 * termination, while others may support lower overhead schemes where
784 * soft breakpoints embedded in the algorithm automatically terminate the
785 * algorithm.
786 *
787 * @param target used to run the algorithm
788 * @param arch_info target-specific description of the algorithm.
789 */
790 int target_run_algorithm(struct target *target,
791 int num_mem_params, struct mem_param *mem_params,
792 int num_reg_params, struct reg_param *reg_param,
793 uint32_t entry_point, uint32_t exit_point,
794 int timeout_ms, void *arch_info)
795 {
796 int retval = ERROR_FAIL;
797
798 if (!target_was_examined(target)) {
799 LOG_ERROR("Target not examined yet");
800 goto done;
801 }
802 if (!target->type->run_algorithm) {
803 LOG_ERROR("Target type '%s' does not support %s",
804 target_type_name(target), __func__);
805 goto done;
806 }
807
808 target->running_alg = true;
809 retval = target->type->run_algorithm(target,
810 num_mem_params, mem_params,
811 num_reg_params, reg_param,
812 entry_point, exit_point, timeout_ms, arch_info);
813 target->running_alg = false;
814
815 done:
816 return retval;
817 }
818
819 /**
820 * Executes a target-specific native code algorithm and leaves it running.
821 *
822 * @param target used to run the algorithm
823 * @param arch_info target-specific description of the algorithm.
824 */
825 int target_start_algorithm(struct target *target,
826 int num_mem_params, struct mem_param *mem_params,
827 int num_reg_params, struct reg_param *reg_params,
828 uint32_t entry_point, uint32_t exit_point,
829 void *arch_info)
830 {
831 int retval = ERROR_FAIL;
832
833 if (!target_was_examined(target)) {
834 LOG_ERROR("Target not examined yet");
835 goto done;
836 }
837 if (!target->type->start_algorithm) {
838 LOG_ERROR("Target type '%s' does not support %s",
839 target_type_name(target), __func__);
840 goto done;
841 }
842 if (target->running_alg) {
843 LOG_ERROR("Target is already running an algorithm");
844 goto done;
845 }
846
847 target->running_alg = true;
848 retval = target->type->start_algorithm(target,
849 num_mem_params, mem_params,
850 num_reg_params, reg_params,
851 entry_point, exit_point, arch_info);
852
853 done:
854 return retval;
855 }
856
857 /**
858 * Waits for an algorithm started with target_start_algorithm() to complete.
859 *
860 * @param target used to run the algorithm
861 * @param arch_info target-specific description of the algorithm.
862 */
863 int target_wait_algorithm(struct target *target,
864 int num_mem_params, struct mem_param *mem_params,
865 int num_reg_params, struct reg_param *reg_params,
866 uint32_t exit_point, int timeout_ms,
867 void *arch_info)
868 {
869 int retval = ERROR_FAIL;
870
871 if (!target->type->wait_algorithm) {
872 LOG_ERROR("Target type '%s' does not support %s",
873 target_type_name(target), __func__);
874 goto done;
875 }
876 if (!target->running_alg) {
877 LOG_ERROR("Target is not running an algorithm");
878 goto done;
879 }
880
881 retval = target->type->wait_algorithm(target,
882 num_mem_params, mem_params,
883 num_reg_params, reg_params,
884 exit_point, timeout_ms, arch_info);
885 if (retval != ERROR_TARGET_TIMEOUT)
886 target->running_alg = false;
887
888 done:
889 return retval;
890 }
891
892 /**
893 * Streams data to a circular buffer on target intended for consumption by code
894 * running asynchronously on target.
895 *
896 * This is intended for applications where target-specific native code runs
897 * on the target, receives data from the circular buffer, does something with
898 * it (most likely writing it to a flash memory), and advances the circular
899 * buffer pointer.
900 *
901 * This assumes that the helper algorithm has already been loaded to the target,
902 * but has not been started yet. Given memory and register parameters are passed
903 * to the algorithm.
904 *
905 * The buffer is defined by (buffer_start, buffer_size) arguments and has the
906 * following format:
907 *
908 * [buffer_start + 0, buffer_start + 4):
909 * Write Pointer address (aka head). Written and updated by this
910 * routine when new data is written to the circular buffer.
911 * [buffer_start + 4, buffer_start + 8):
912 * Read Pointer address (aka tail). Updated by code running on the
913 * target after it consumes data.
914 * [buffer_start + 8, buffer_start + buffer_size):
915 * Circular buffer contents.
916 *
917 * See contrib/loaders/flash/stm32f1x.S for an example.
918 *
919 * @param target used to run the algorithm
920 * @param buffer address on the host where data to be sent is located
921 * @param count number of blocks to send
922 * @param block_size size in bytes of each block
923 * @param num_mem_params count of memory-based params to pass to algorithm
924 * @param mem_params memory-based params to pass to algorithm
925 * @param num_reg_params count of register-based params to pass to algorithm
926 * @param reg_params memory-based params to pass to algorithm
927 * @param buffer_start address on the target of the circular buffer structure
928 * @param buffer_size size of the circular buffer structure
929 * @param entry_point address on the target to execute to start the algorithm
930 * @param exit_point address at which to set a breakpoint to catch the
931 * end of the algorithm; can be 0 if target triggers a breakpoint itself
932 */
933
934 int target_run_flash_async_algorithm(struct target *target,
935 const uint8_t *buffer, uint32_t count, int block_size,
936 int num_mem_params, struct mem_param *mem_params,
937 int num_reg_params, struct reg_param *reg_params,
938 uint32_t buffer_start, uint32_t buffer_size,
939 uint32_t entry_point, uint32_t exit_point, void *arch_info)
940 {
941 int retval;
942 int timeout = 0;
943
944 const uint8_t *buffer_orig = buffer;
945
946 /* Set up working area. First word is write pointer, second word is read pointer,
947 * rest is fifo data area. */
948 uint32_t wp_addr = buffer_start;
949 uint32_t rp_addr = buffer_start + 4;
950 uint32_t fifo_start_addr = buffer_start + 8;
951 uint32_t fifo_end_addr = buffer_start + buffer_size;
952
953 uint32_t wp = fifo_start_addr;
954 uint32_t rp = fifo_start_addr;
955
956 /* validate block_size is 2^n */
957 assert(!block_size || !(block_size & (block_size - 1)));
958
959 retval = target_write_u32(target, wp_addr, wp);
960 if (retval != ERROR_OK)
961 return retval;
962 retval = target_write_u32(target, rp_addr, rp);
963 if (retval != ERROR_OK)
964 return retval;
965
966 /* Start up algorithm on target and let it idle while writing the first chunk */
967 retval = target_start_algorithm(target, num_mem_params, mem_params,
968 num_reg_params, reg_params,
969 entry_point,
970 exit_point,
971 arch_info);
972
973 if (retval != ERROR_OK) {
974 LOG_ERROR("error starting target flash write algorithm");
975 return retval;
976 }
977
978 while (count > 0) {
979
980 retval = target_read_u32(target, rp_addr, &rp);
981 if (retval != ERROR_OK) {
982 LOG_ERROR("failed to get read pointer");
983 break;
984 }
985
986 LOG_DEBUG("offs 0x%zx count 0x%" PRIx32 " wp 0x%" PRIx32 " rp 0x%" PRIx32,
987 (size_t) (buffer - buffer_orig), count, wp, rp);
988
989 if (rp == 0) {
990 LOG_ERROR("flash write algorithm aborted by target");
991 retval = ERROR_FLASH_OPERATION_FAILED;
992 break;
993 }
994
995 if (((rp - fifo_start_addr) & (block_size - 1)) || rp < fifo_start_addr || rp >= fifo_end_addr) {
996 LOG_ERROR("corrupted fifo read pointer 0x%" PRIx32, rp);
997 break;
998 }
999
1000 /* Count the number of bytes available in the fifo without
1001 * crossing the wrap around. Make sure to not fill it completely,
1002 * because that would make wp == rp and that's the empty condition. */
1003 uint32_t thisrun_bytes;
1004 if (rp > wp)
1005 thisrun_bytes = rp - wp - block_size;
1006 else if (rp > fifo_start_addr)
1007 thisrun_bytes = fifo_end_addr - wp;
1008 else
1009 thisrun_bytes = fifo_end_addr - wp - block_size;
1010
1011 if (thisrun_bytes == 0) {
1012 /* Throttle polling a bit if transfer is (much) faster than flash
1013 * programming. The exact delay shouldn't matter as long as it's
1014 * less than buffer size / flash speed. This is very unlikely to
1015 * run when using high latency connections such as USB. */
1016 alive_sleep(10);
1017
1018 /* to stop an infinite loop on some targets check and increment a timeout
1019 * this issue was observed on a stellaris using the new ICDI interface */
1020 if (timeout++ >= 500) {
1021 LOG_ERROR("timeout waiting for algorithm, a target reset is recommended");
1022 return ERROR_FLASH_OPERATION_FAILED;
1023 }
1024 continue;
1025 }
1026
1027 /* reset our timeout */
1028 timeout = 0;
1029
1030 /* Limit to the amount of data we actually want to write */
1031 if (thisrun_bytes > count * block_size)
1032 thisrun_bytes = count * block_size;
1033
1034 /* Write data to fifo */
1035 retval = target_write_buffer(target, wp, thisrun_bytes, buffer);
1036 if (retval != ERROR_OK)
1037 break;
1038
1039 /* Update counters and wrap write pointer */
1040 buffer += thisrun_bytes;
1041 count -= thisrun_bytes / block_size;
1042 wp += thisrun_bytes;
1043 if (wp >= fifo_end_addr)
1044 wp = fifo_start_addr;
1045
1046 /* Store updated write pointer to target */
1047 retval = target_write_u32(target, wp_addr, wp);
1048 if (retval != ERROR_OK)
1049 break;
1050
1051 /* Avoid GDB timeouts */
1052 keep_alive();
1053 }
1054
1055 if (retval != ERROR_OK) {
1056 /* abort flash write algorithm on target */
1057 target_write_u32(target, wp_addr, 0);
1058 }
1059
1060 int retval2 = target_wait_algorithm(target, num_mem_params, mem_params,
1061 num_reg_params, reg_params,
1062 exit_point,
1063 10000,
1064 arch_info);
1065
1066 if (retval2 != ERROR_OK) {
1067 LOG_ERROR("error waiting for target flash write algorithm");
1068 retval = retval2;
1069 }
1070
1071 if (retval == ERROR_OK) {
1072 /* check if algorithm set rp = 0 after fifo writer loop finished */
1073 retval = target_read_u32(target, rp_addr, &rp);
1074 if (retval == ERROR_OK && rp == 0) {
1075 LOG_ERROR("flash write algorithm aborted by target");
1076 retval = ERROR_FLASH_OPERATION_FAILED;
1077 }
1078 }
1079
1080 return retval;
1081 }
1082
1083 int target_read_memory(struct target *target,
1084 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1085 {
1086 if (!target_was_examined(target)) {
1087 LOG_ERROR("Target not examined yet");
1088 return ERROR_FAIL;
1089 }
1090 if (!target->type->read_memory) {
1091 LOG_ERROR("Target %s doesn't support read_memory", target_name(target));
1092 return ERROR_FAIL;
1093 }
1094 return target->type->read_memory(target, address, size, count, buffer);
1095 }
1096
1097 int target_read_phys_memory(struct target *target,
1098 target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
1099 {
1100 if (!target_was_examined(target)) {
1101 LOG_ERROR("Target not examined yet");
1102 return ERROR_FAIL;
1103 }
1104 if (!target->type->read_phys_memory) {
1105 LOG_ERROR("Target %s doesn't support read_phys_memory", target_name(target));
1106 return ERROR_FAIL;
1107 }
1108 return target->type->read_phys_memory(target, address, size, count, buffer);
1109 }
1110
1111 int target_write_memory(struct target *target,
1112 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1113 {
1114 if (!target_was_examined(target)) {
1115 LOG_ERROR("Target not examined yet");
1116 return ERROR_FAIL;
1117 }
1118 if (!target->type->write_memory) {
1119 LOG_ERROR("Target %s doesn't support write_memory", target_name(target));
1120 return ERROR_FAIL;
1121 }
1122 return target->type->write_memory(target, address, size, count, buffer);
1123 }
1124
1125 int target_write_phys_memory(struct target *target,
1126 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
1127 {
1128 if (!target_was_examined(target)) {
1129 LOG_ERROR("Target not examined yet");
1130 return ERROR_FAIL;
1131 }
1132 if (!target->type->write_phys_memory) {
1133 LOG_ERROR("Target %s doesn't support write_phys_memory", target_name(target));
1134 return ERROR_FAIL;
1135 }
1136 return target->type->write_phys_memory(target, address, size, count, buffer);
1137 }
1138
1139 int target_add_breakpoint(struct target *target,
1140 struct breakpoint *breakpoint)
1141 {
1142 if ((target->state != TARGET_HALTED) && (breakpoint->type != BKPT_HARD)) {
1143 LOG_WARNING("target %s is not halted (add breakpoint)", target_name(target));
1144 return ERROR_TARGET_NOT_HALTED;
1145 }
1146 return target->type->add_breakpoint(target, breakpoint);
1147 }
1148
1149 int target_add_context_breakpoint(struct target *target,
1150 struct breakpoint *breakpoint)
1151 {
1152 if (target->state != TARGET_HALTED) {
1153 LOG_WARNING("target %s is not halted (add context breakpoint)", target_name(target));
1154 return ERROR_TARGET_NOT_HALTED;
1155 }
1156 return target->type->add_context_breakpoint(target, breakpoint);
1157 }
1158
1159 int target_add_hybrid_breakpoint(struct target *target,
1160 struct breakpoint *breakpoint)
1161 {
1162 if (target->state != TARGET_HALTED) {
1163 LOG_WARNING("target %s is not halted (add hybrid breakpoint)", target_name(target));
1164 return ERROR_TARGET_NOT_HALTED;
1165 }
1166 return target->type->add_hybrid_breakpoint(target, breakpoint);
1167 }
1168
1169 int target_remove_breakpoint(struct target *target,
1170 struct breakpoint *breakpoint)
1171 {
1172 return target->type->remove_breakpoint(target, breakpoint);
1173 }
1174
1175 int target_add_watchpoint(struct target *target,
1176 struct watchpoint *watchpoint)
1177 {
1178 if (target->state != TARGET_HALTED) {
1179 LOG_WARNING("target %s is not halted (add watchpoint)", target_name(target));
1180 return ERROR_TARGET_NOT_HALTED;
1181 }
1182 return target->type->add_watchpoint(target, watchpoint);
1183 }
1184 int target_remove_watchpoint(struct target *target,
1185 struct watchpoint *watchpoint)
1186 {
1187 return target->type->remove_watchpoint(target, watchpoint);
1188 }
1189 int target_hit_watchpoint(struct target *target,
1190 struct watchpoint **hit_watchpoint)
1191 {
1192 if (target->state != TARGET_HALTED) {
1193 LOG_WARNING("target %s is not halted (hit watchpoint)", target->cmd_name);
1194 return ERROR_TARGET_NOT_HALTED;
1195 }
1196
1197 if (target->type->hit_watchpoint == NULL) {
1198 /* For backward compatible, if hit_watchpoint is not implemented,
1199 * return ERROR_FAIL such that gdb_server will not take the nonsense
1200 * information. */
1201 return ERROR_FAIL;
1202 }
1203
1204 return target->type->hit_watchpoint(target, hit_watchpoint);
1205 }
1206
1207 const char *target_get_gdb_arch(struct target *target)
1208 {
1209 if (target->type->get_gdb_arch == NULL)
1210 return NULL;
1211 return target->type->get_gdb_arch(target);
1212 }
1213
1214 int target_get_gdb_reg_list(struct target *target,
1215 struct reg **reg_list[], int *reg_list_size,
1216 enum target_register_class reg_class)
1217 {
1218 int result = target->type->get_gdb_reg_list(target, reg_list,
1219 reg_list_size, reg_class);
1220 if (result != ERROR_OK) {
1221 *reg_list = NULL;
1222 *reg_list_size = 0;
1223 }
1224 return result;
1225 }
1226
1227 int target_get_gdb_reg_list_noread(struct target *target,
1228 struct reg **reg_list[], int *reg_list_size,
1229 enum target_register_class reg_class)
1230 {
1231 if (target->type->get_gdb_reg_list_noread &&
1232 target->type->get_gdb_reg_list_noread(target, reg_list,
1233 reg_list_size, reg_class) == ERROR_OK)
1234 return ERROR_OK;
1235 return target_get_gdb_reg_list(target, reg_list, reg_list_size, reg_class);
1236 }
1237
1238 bool target_supports_gdb_connection(struct target *target)
1239 {
1240 /*
1241 * based on current code, we can simply exclude all the targets that
1242 * don't provide get_gdb_reg_list; this could change with new targets.
1243 */
1244 return !!target->type->get_gdb_reg_list;
1245 }
1246
1247 int target_step(struct target *target,
1248 int current, target_addr_t address, int handle_breakpoints)
1249 {
1250 return target->type->step(target, current, address, handle_breakpoints);
1251 }
1252
1253 int target_get_gdb_fileio_info(struct target *target, struct gdb_fileio_info *fileio_info)
1254 {
1255 if (target->state != TARGET_HALTED) {
1256 LOG_WARNING("target %s is not halted (gdb fileio)", target->cmd_name);
1257 return ERROR_TARGET_NOT_HALTED;
1258 }
1259 return target->type->get_gdb_fileio_info(target, fileio_info);
1260 }
1261
1262 int target_gdb_fileio_end(struct target *target, int retcode, int fileio_errno, bool ctrl_c)
1263 {
1264 if (target->state != TARGET_HALTED) {
1265 LOG_WARNING("target %s is not halted (gdb fileio end)", target->cmd_name);
1266 return ERROR_TARGET_NOT_HALTED;
1267 }
1268 return target->type->gdb_fileio_end(target, retcode, fileio_errno, ctrl_c);
1269 }
1270
1271 target_addr_t target_address_max(struct target *target)
1272 {
1273 unsigned bits = target_address_bits(target);
1274 if (sizeof(target_addr_t) * 8 == bits)
1275 return (target_addr_t) -1;
1276 else
1277 return (((target_addr_t) 1) << bits) - 1;
1278 }
1279
1280 unsigned target_address_bits(struct target *target)
1281 {
1282 if (target->type->address_bits)
1283 return target->type->address_bits(target);
1284 return 32;
1285 }
1286
1287 int target_profiling(struct target *target, uint32_t *samples,
1288 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
1289 {
1290 if (target->state != TARGET_HALTED) {
1291 LOG_WARNING("target %s is not halted (profiling)", target->cmd_name);
1292 return ERROR_TARGET_NOT_HALTED;
1293 }
1294 return target->type->profiling(target, samples, max_num_samples,
1295 num_samples, seconds);
1296 }
1297
1298 /**
1299 * Reset the @c examined flag for the given target.
1300 * Pure paranoia -- targets are zeroed on allocation.
1301 */
1302 static void target_reset_examined(struct target *target)
1303 {
1304 target->examined = false;
1305 }
1306
1307 static int handle_target(void *priv);
1308
1309 static int target_init_one(struct command_context *cmd_ctx,
1310 struct target *target)
1311 {
1312 target_reset_examined(target);
1313
1314 struct target_type *type = target->type;
1315 if (type->examine == NULL)
1316 type->examine = default_examine;
1317
1318 if (type->check_reset == NULL)
1319 type->check_reset = default_check_reset;
1320
1321 assert(type->init_target != NULL);
1322
1323 int retval = type->init_target(cmd_ctx, target);
1324 if (ERROR_OK != retval) {
1325 LOG_ERROR("target '%s' init failed", target_name(target));
1326 return retval;
1327 }
1328
1329 /* Sanity-check MMU support ... stub in what we must, to help
1330 * implement it in stages, but warn if we need to do so.
1331 */
1332 if (type->mmu) {
1333 if (type->virt2phys == NULL) {
1334 LOG_ERROR("type '%s' is missing virt2phys", type->name);
1335 type->virt2phys = identity_virt2phys;
1336 }
1337 } else {
1338 /* Make sure no-MMU targets all behave the same: make no
1339 * distinction between physical and virtual addresses, and
1340 * ensure that virt2phys() is always an identity mapping.
1341 */
1342 if (type->write_phys_memory || type->read_phys_memory || type->virt2phys)
1343 LOG_WARNING("type '%s' has bad MMU hooks", type->name);
1344
1345 type->mmu = no_mmu;
1346 type->write_phys_memory = type->write_memory;
1347 type->read_phys_memory = type->read_memory;
1348 type->virt2phys = identity_virt2phys;
1349 }
1350
1351 if (target->type->read_buffer == NULL)
1352 target->type->read_buffer = target_read_buffer_default;
1353
1354 if (target->type->write_buffer == NULL)
1355 target->type->write_buffer = target_write_buffer_default;
1356
1357 if (target->type->get_gdb_fileio_info == NULL)
1358 target->type->get_gdb_fileio_info = target_get_gdb_fileio_info_default;
1359
1360 if (target->type->gdb_fileio_end == NULL)
1361 target->type->gdb_fileio_end = target_gdb_fileio_end_default;
1362
1363 if (target->type->profiling == NULL)
1364 target->type->profiling = target_profiling_default;
1365
1366 return ERROR_OK;
1367 }
1368
1369 static int target_init(struct command_context *cmd_ctx)
1370 {
1371 struct target *target;
1372 int retval;
1373
1374 for (target = all_targets; target; target = target->next) {
1375 retval = target_init_one(cmd_ctx, target);
1376 if (ERROR_OK != retval)
1377 return retval;
1378 }
1379
1380 if (!all_targets)
1381 return ERROR_OK;
1382
1383 retval = target_register_user_commands(cmd_ctx);
1384 if (ERROR_OK != retval)
1385 return retval;
1386
1387 retval = target_register_timer_callback(&handle_target,
1388 polling_interval, TARGET_TIMER_TYPE_PERIODIC, cmd_ctx->interp);
1389 if (ERROR_OK != retval)
1390 return retval;
1391
1392 return ERROR_OK;
1393 }
1394
1395 COMMAND_HANDLER(handle_target_init_command)
1396 {
1397 int retval;
1398
1399 if (CMD_ARGC != 0)
1400 return ERROR_COMMAND_SYNTAX_ERROR;
1401
1402 static bool target_initialized;
1403 if (target_initialized) {
1404 LOG_INFO("'target init' has already been called");
1405 return ERROR_OK;
1406 }
1407 target_initialized = true;
1408
1409 retval = command_run_line(CMD_CTX, "init_targets");
1410 if (ERROR_OK != retval)
1411 return retval;
1412
1413 retval = command_run_line(CMD_CTX, "init_target_events");
1414 if (ERROR_OK != retval)
1415 return retval;
1416
1417 retval = command_run_line(CMD_CTX, "init_board");
1418 if (ERROR_OK != retval)
1419 return retval;
1420
1421 LOG_DEBUG("Initializing targets...");
1422 return target_init(CMD_CTX);
1423 }
1424
1425 int target_register_event_callback(int (*callback)(struct target *target,
1426 enum target_event event, void *priv), void *priv)
1427 {
1428 struct target_event_callback **callbacks_p = &target_event_callbacks;
1429
1430 if (callback == NULL)
1431 return ERROR_COMMAND_SYNTAX_ERROR;
1432
1433 if (*callbacks_p) {
1434 while ((*callbacks_p)->next)
1435 callbacks_p = &((*callbacks_p)->next);
1436 callbacks_p = &((*callbacks_p)->next);
1437 }
1438
1439 (*callbacks_p) = malloc(sizeof(struct target_event_callback));
1440 (*callbacks_p)->callback = callback;
1441 (*callbacks_p)->priv = priv;
1442 (*callbacks_p)->next = NULL;
1443
1444 return ERROR_OK;
1445 }
1446
1447 int target_register_reset_callback(int (*callback)(struct target *target,
1448 enum target_reset_mode reset_mode, void *priv), void *priv)
1449 {
1450 struct target_reset_callback *entry;
1451
1452 if (callback == NULL)
1453 return ERROR_COMMAND_SYNTAX_ERROR;
1454
1455 entry = malloc(sizeof(struct target_reset_callback));
1456 if (entry == NULL) {
1457 LOG_ERROR("error allocating buffer for reset callback entry");
1458 return ERROR_COMMAND_SYNTAX_ERROR;
1459 }
1460
1461 entry->callback = callback;
1462 entry->priv = priv;
1463 list_add(&entry->list, &target_reset_callback_list);
1464
1465
1466 return ERROR_OK;
1467 }
1468
1469 int target_register_trace_callback(int (*callback)(struct target *target,
1470 size_t len, uint8_t *data, void *priv), void *priv)
1471 {
1472 struct target_trace_callback *entry;
1473
1474 if (callback == NULL)
1475 return ERROR_COMMAND_SYNTAX_ERROR;
1476
1477 entry = malloc(sizeof(struct target_trace_callback));
1478 if (entry == NULL) {
1479 LOG_ERROR("error allocating buffer for trace callback entry");
1480 return ERROR_COMMAND_SYNTAX_ERROR;
1481 }
1482
1483 entry->callback = callback;
1484 entry->priv = priv;
1485 list_add(&entry->list, &target_trace_callback_list);
1486
1487
1488 return ERROR_OK;
1489 }
1490
1491 int target_register_timer_callback(int (*callback)(void *priv),
1492 unsigned int time_ms, enum target_timer_type type, void *priv)
1493 {
1494 struct target_timer_callback **callbacks_p = &target_timer_callbacks;
1495
1496 if (callback == NULL)
1497 return ERROR_COMMAND_SYNTAX_ERROR;
1498
1499 if (*callbacks_p) {
1500 while ((*callbacks_p)->next)
1501 callbacks_p = &((*callbacks_p)->next);
1502 callbacks_p = &((*callbacks_p)->next);
1503 }
1504
1505 (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
1506 (*callbacks_p)->callback = callback;
1507 (*callbacks_p)->type = type;
1508 (*callbacks_p)->time_ms = time_ms;
1509 (*callbacks_p)->removed = false;
1510
1511 gettimeofday(&(*callbacks_p)->when, NULL);
1512 timeval_add_time(&(*callbacks_p)->when, 0, time_ms * 1000);
1513
1514 (*callbacks_p)->priv = priv;
1515 (*callbacks_p)->next = NULL;
1516
1517 return ERROR_OK;
1518 }
1519
1520 int target_unregister_event_callback(int (*callback)(struct target *target,
1521 enum target_event event, void *priv), void *priv)
1522 {
1523 struct target_event_callback **p = &target_event_callbacks;
1524 struct target_event_callback *c = target_event_callbacks;
1525
1526 if (callback == NULL)
1527 return ERROR_COMMAND_SYNTAX_ERROR;
1528
1529 while (c) {
1530 struct target_event_callback *next = c->next;
1531 if ((c->callback == callback) && (c->priv == priv)) {
1532 *p = next;
1533 free(c);
1534 return ERROR_OK;
1535 } else
1536 p = &(c->next);
1537 c = next;
1538 }
1539
1540 return ERROR_OK;
1541 }
1542
1543 int target_unregister_reset_callback(int (*callback)(struct target *target,
1544 enum target_reset_mode reset_mode, void *priv), void *priv)
1545 {
1546 struct target_reset_callback *entry;
1547
1548 if (callback == NULL)
1549 return ERROR_COMMAND_SYNTAX_ERROR;
1550
1551 list_for_each_entry(entry, &target_reset_callback_list, list) {
1552 if (entry->callback == callback && entry->priv == priv) {
1553 list_del(&entry->list);
1554 free(entry);
1555 break;
1556 }
1557 }
1558
1559 return ERROR_OK;
1560 }
1561
1562 int target_unregister_trace_callback(int (*callback)(struct target *target,
1563 size_t len, uint8_t *data, void *priv), void *priv)
1564 {
1565 struct target_trace_callback *entry;
1566
1567 if (callback == NULL)
1568 return ERROR_COMMAND_SYNTAX_ERROR;
1569
1570 list_for_each_entry(entry, &target_trace_callback_list, list) {
1571 if (entry->callback == callback && entry->priv == priv) {
1572 list_del(&entry->list);
1573 free(entry);
1574 break;
1575 }
1576 }
1577
1578 return ERROR_OK;
1579 }
1580
1581 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1582 {
1583 if (callback == NULL)
1584 return ERROR_COMMAND_SYNTAX_ERROR;
1585
1586 for (struct target_timer_callback *c = target_timer_callbacks;
1587 c; c = c->next) {
1588 if ((c->callback == callback) && (c->priv == priv)) {
1589 c->removed = true;
1590 return ERROR_OK;
1591 }
1592 }
1593
1594 return ERROR_FAIL;
1595 }
1596
1597 int target_call_event_callbacks(struct target *target, enum target_event event)
1598 {
1599 struct target_event_callback *callback = target_event_callbacks;
1600 struct target_event_callback *next_callback;
1601
1602 if (event == TARGET_EVENT_HALTED) {
1603 /* execute early halted first */
1604 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1605 }
1606
1607 LOG_DEBUG("target event %i (%s) for core %s", event,
1608 Jim_Nvp_value2name_simple(nvp_target_event, event)->name,
1609 target_name(target));
1610
1611 target_handle_event(target, event);
1612
1613 while (callback) {
1614 next_callback = callback->next;
1615 callback->callback(target, event, callback->priv);
1616 callback = next_callback;
1617 }
1618
1619 return ERROR_OK;
1620 }
1621
1622 int target_call_reset_callbacks(struct target *target, enum target_reset_mode reset_mode)
1623 {
1624 struct target_reset_callback *callback;
1625
1626 LOG_DEBUG("target reset %i (%s)", reset_mode,
1627 Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode)->name);
1628
1629 list_for_each_entry(callback, &target_reset_callback_list, list)
1630 callback->callback(target, reset_mode, callback->priv);
1631
1632 return ERROR_OK;
1633 }
1634
1635 int target_call_trace_callbacks(struct target *target, size_t len, uint8_t *data)
1636 {
1637 struct target_trace_callback *callback;
1638
1639 list_for_each_entry(callback, &target_trace_callback_list, list)
1640 callback->callback(target, len, data, callback->priv);
1641
1642 return ERROR_OK;
1643 }
1644
1645 static int target_timer_callback_periodic_restart(
1646 struct target_timer_callback *cb, struct timeval *now)
1647 {
1648 cb->when = *now;
1649 timeval_add_time(&cb->when, 0, cb->time_ms * 1000L);
1650 return ERROR_OK;
1651 }
1652
1653 static int target_call_timer_callback(struct target_timer_callback *cb,
1654 struct timeval *now)
1655 {
1656 cb->callback(cb->priv);
1657
1658 if (cb->type == TARGET_TIMER_TYPE_PERIODIC)
1659 return target_timer_callback_periodic_restart(cb, now);
1660
1661 return target_unregister_timer_callback(cb->callback, cb->priv);
1662 }
1663
1664 static int target_call_timer_callbacks_check_time(int checktime)
1665 {
1666 static bool callback_processing;
1667
1668 /* Do not allow nesting */
1669 if (callback_processing)
1670 return ERROR_OK;
1671
1672 callback_processing = true;
1673
1674 keep_alive();
1675
1676 struct timeval now;
1677 gettimeofday(&now, NULL);
1678
1679 /* Store an address of the place containing a pointer to the
1680 * next item; initially, that's a standalone "root of the
1681 * list" variable. */
1682 struct target_timer_callback **callback = &target_timer_callbacks;
1683 while (*callback) {
1684 if ((*callback)->removed) {
1685 struct target_timer_callback *p = *callback;
1686 *callback = (*callback)->next;
1687 free(p);
1688 continue;
1689 }
1690
1691 bool call_it = (*callback)->callback &&
1692 ((!checktime && (*callback)->type == TARGET_TIMER_TYPE_PERIODIC) ||
1693 timeval_compare(&now, &(*callback)->when) >= 0);
1694
1695 if (call_it)
1696 target_call_timer_callback(*callback, &now);
1697
1698 callback = &(*callback)->next;
1699 }
1700
1701 callback_processing = false;
1702 return ERROR_OK;
1703 }
1704
1705 int target_call_timer_callbacks(void)
1706 {
1707 return target_call_timer_callbacks_check_time(1);
1708 }
1709
1710 /* invoke periodic callbacks immediately */
1711 int target_call_timer_callbacks_now(void)
1712 {
1713 return target_call_timer_callbacks_check_time(0);
1714 }
1715
1716 /* Prints the working area layout for debug purposes */
1717 static void print_wa_layout(struct target *target)
1718 {
1719 struct working_area *c = target->working_areas;
1720
1721 while (c) {
1722 LOG_DEBUG("%c%c " TARGET_ADDR_FMT "-" TARGET_ADDR_FMT " (%" PRIu32 " bytes)",
1723 c->backup ? 'b' : ' ', c->free ? ' ' : '*',
1724 c->address, c->address + c->size - 1, c->size);
1725 c = c->next;
1726 }
1727 }
1728
1729 /* Reduce area to size bytes, create a new free area from the remaining bytes, if any. */
1730 static void target_split_working_area(struct working_area *area, uint32_t size)
1731 {
1732 assert(area->free); /* Shouldn't split an allocated area */
1733 assert(size <= area->size); /* Caller should guarantee this */
1734
1735 /* Split only if not already the right size */
1736 if (size < area->size) {
1737 struct working_area *new_wa = malloc(sizeof(*new_wa));
1738
1739 if (new_wa == NULL)
1740 return;
1741
1742 new_wa->next = area->next;
1743 new_wa->size = area->size - size;
1744 new_wa->address = area->address + size;
1745 new_wa->backup = NULL;
1746 new_wa->user = NULL;
1747 new_wa->free = true;
1748
1749 area->next = new_wa;
1750 area->size = size;
1751
1752 /* If backup memory was allocated to this area, it has the wrong size
1753 * now so free it and it will be reallocated if/when needed */
1754 if (area->backup) {
1755 free(area->backup);
1756 area->backup = NULL;
1757 }
1758 }
1759 }
1760
1761 /* Merge all adjacent free areas into one */
1762 static void target_merge_working_areas(struct target *target)
1763 {
1764 struct working_area *c = target->working_areas;
1765
1766 while (c && c->next) {
1767 assert(c->next->address == c->address + c->size); /* This is an invariant */
1768
1769 /* Find two adjacent free areas */
1770 if (c->free && c->next->free) {
1771 /* Merge the last into the first */
1772 c->size += c->next->size;
1773
1774 /* Remove the last */
1775 struct working_area *to_be_freed = c->next;
1776 c->next = c->next->next;
1777 if (to_be_freed->backup)
1778 free(to_be_freed->backup);
1779 free(to_be_freed);
1780
1781 /* If backup memory was allocated to the remaining area, it's has
1782 * the wrong size now */
1783 if (c->backup) {
1784 free(c->backup);
1785 c->backup = NULL;
1786 }
1787 } else {
1788 c = c->next;
1789 }
1790 }
1791 }
1792
1793 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1794 {
1795 /* Reevaluate working area address based on MMU state*/
1796 if (target->working_areas == NULL) {
1797 int retval;
1798 int enabled;
1799
1800 retval = target->type->mmu(target, &enabled);
1801 if (retval != ERROR_OK)
1802 return retval;
1803
1804 if (!enabled) {
1805 if (target->working_area_phys_spec) {
1806 LOG_DEBUG("MMU disabled, using physical "
1807 "address for working memory " TARGET_ADDR_FMT,
1808 target->working_area_phys);
1809 target->working_area = target->working_area_phys;
1810 } else {
1811 LOG_ERROR("No working memory available. "
1812 "Specify -work-area-phys to target.");
1813 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1814 }
1815 } else {
1816 if (target->working_area_virt_spec) {
1817 LOG_DEBUG("MMU enabled, using virtual "
1818 "address for working memory " TARGET_ADDR_FMT,
1819 target->working_area_virt);
1820 target->working_area = target->working_area_virt;
1821 } else {
1822 LOG_ERROR("No working memory available. "
1823 "Specify -work-area-virt to target.");
1824 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1825 }
1826 }
1827
1828 /* Set up initial working area on first call */
1829 struct working_area *new_wa = malloc(sizeof(*new_wa));
1830 if (new_wa) {
1831 new_wa->next = NULL;
1832 new_wa->size = target->working_area_size & ~3UL; /* 4-byte align */
1833 new_wa->address = target->working_area;
1834 new_wa->backup = NULL;
1835 new_wa->user = NULL;
1836 new_wa->free = true;
1837 }
1838
1839 target->working_areas = new_wa;
1840 }
1841
1842 /* only allocate multiples of 4 byte */
1843 if (size % 4)
1844 size = (size + 3) & (~3UL);
1845
1846 struct working_area *c = target->working_areas;
1847
1848 /* Find the first large enough working area */
1849 while (c) {
1850 if (c->free && c->size >= size)
1851 break;
1852 c = c->next;
1853 }
1854
1855 if (c == NULL)
1856 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1857
1858 /* Split the working area into the requested size */
1859 target_split_working_area(c, size);
1860
1861 LOG_DEBUG("allocated new working area of %" PRIu32 " bytes at address " TARGET_ADDR_FMT,
1862 size, c->address);
1863
1864 if (target->backup_working_area) {
1865 if (c->backup == NULL) {
1866 c->backup = malloc(c->size);
1867 if (c->backup == NULL)
1868 return ERROR_FAIL;
1869 }
1870
1871 int retval = target_read_memory(target, c->address, 4, c->size / 4, c->backup);
1872 if (retval != ERROR_OK)
1873 return retval;
1874 }
1875
1876 /* mark as used, and return the new (reused) area */
1877 c->free = false;
1878 *area = c;
1879
1880 /* user pointer */
1881 c->user = area;
1882
1883 print_wa_layout(target);
1884
1885 return ERROR_OK;
1886 }
1887
1888 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1889 {
1890 int retval;
1891
1892 retval = target_alloc_working_area_try(target, size, area);
1893 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1894 LOG_WARNING("not enough working area available(requested %"PRIu32")", size);
1895 return retval;
1896
1897 }
1898
1899 static int target_restore_working_area(struct target *target, struct working_area *area)
1900 {
1901 int retval = ERROR_OK;
1902
1903 if (target->backup_working_area && area->backup != NULL) {
1904 retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup);
1905 if (retval != ERROR_OK)
1906 LOG_ERROR("failed to restore %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
1907 area->size, area->address);
1908 }
1909
1910 return retval;
1911 }
1912
1913 /* Restore the area's backup memory, if any, and return the area to the allocation pool */
1914 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1915 {
1916 int retval = ERROR_OK;
1917
1918 if (area->free)
1919 return retval;
1920
1921 if (restore) {
1922 retval = target_restore_working_area(target, area);
1923 /* REVISIT: Perhaps the area should be freed even if restoring fails. */
1924 if (retval != ERROR_OK)
1925 return retval;
1926 }
1927
1928 area->free = true;
1929
1930 LOG_DEBUG("freed %" PRIu32 " bytes of working area at address " TARGET_ADDR_FMT,
1931 area->size, area->address);
1932
1933 /* mark user pointer invalid */
1934 /* TODO: Is this really safe? It points to some previous caller's memory.
1935 * How could we know that the area pointer is still in that place and not
1936 * some other vital data? What's the purpose of this, anyway? */
1937 *area->user = NULL;
1938 area->user = NULL;
1939
1940 target_merge_working_areas(target);
1941
1942 print_wa_layout(target);
1943
1944 return retval;
1945 }
1946
1947 int target_free_working_area(struct target *target, struct working_area *area)
1948 {
1949 return target_free_working_area_restore(target, area, 1);
1950 }
1951
1952 /* free resources and restore memory, if restoring memory fails,
1953 * free up resources anyway
1954 */
1955 static void target_free_all_working_areas_restore(struct target *target, int restore)
1956 {
1957 struct working_area *c = target->working_areas;
1958
1959 LOG_DEBUG("freeing all working areas");
1960
1961 /* Loop through all areas, restoring the allocated ones and marking them as free */
1962 while (c) {
1963 if (!c->free) {
1964 if (restore)
1965 target_restore_working_area(target, c);
1966 c->free = true;
1967 *c->user = NULL; /* Same as above */
1968 c->user = NULL;
1969 }
1970 c = c->next;
1971 }
1972
1973 /* Run a merge pass to combine all areas into one */
1974 target_merge_working_areas(target);
1975
1976 print_wa_layout(target);
1977 }
1978
1979 void target_free_all_working_areas(struct target *target)
1980 {
1981 target_free_all_working_areas_restore(target, 1);
1982
1983 /* Now we have none or only one working area marked as free */
1984 if (target->working_areas) {
1985 /* Free the last one to allow on-the-fly moving and resizing */
1986 free(target->working_areas->backup);
1987 free(target->working_areas);
1988 target->working_areas = NULL;
1989 }
1990 }
1991
1992 /* Find the largest number of bytes that can be allocated */
1993 uint32_t target_get_working_area_avail(struct target *target)
1994 {
1995 struct working_area *c = target->working_areas;
1996 uint32_t max_size = 0;
1997
1998 if (c == NULL)
1999 return target->working_area_size;
2000
2001 while (c) {
2002 if (c->free && max_size < c->size)
2003 max_size = c->size;
2004
2005 c = c->next;
2006 }
2007
2008 return max_size;
2009 }
2010
2011 static void target_destroy(struct target *target)
2012 {
2013 if (target->type->deinit_target)
2014 target->type->deinit_target(target);
2015
2016 if (target->semihosting)
2017 free(target->semihosting);
2018
2019 jtag_unregister_event_callback(jtag_enable_callback, target);
2020
2021 struct target_event_action *teap = target->event_action;
2022 while (teap) {
2023 struct target_event_action *next = teap->next;
2024 Jim_DecrRefCount(teap->interp, teap->body);
2025 free(teap);
2026 teap = next;
2027 }
2028
2029 target_free_all_working_areas(target);
2030
2031 /* release the targets SMP list */
2032 if (target->smp) {
2033 struct target_list *head = target->head;
2034 while (head != NULL) {
2035 struct target_list *pos = head->next;
2036 head->target->smp = 0;
2037 free(head);
2038 head = pos;
2039 }
2040 target->smp = 0;
2041 }
2042
2043 free(target->gdb_port_override);
2044 free(target->type);
2045 free(target->trace_info);
2046 free(target->fileio_info);
2047 free(target->cmd_name);
2048 free(target);
2049 }
2050
2051 void target_quit(void)
2052 {
2053 struct target_event_callback *pe = target_event_callbacks;
2054 while (pe) {
2055 struct target_event_callback *t = pe->next;
2056 free(pe);
2057 pe = t;
2058 }
2059 target_event_callbacks = NULL;
2060
2061 struct target_timer_callback *pt = target_timer_callbacks;
2062 while (pt) {
2063 struct target_timer_callback *t = pt->next;
2064 free(pt);
2065 pt = t;
2066 }
2067 target_timer_callbacks = NULL;
2068
2069 for (struct target *target = all_targets; target;) {
2070 struct target *tmp;
2071
2072 tmp = target->next;
2073 target_destroy(target);
2074 target = tmp;
2075 }
2076
2077 all_targets = NULL;
2078 }
2079
2080 int target_arch_state(struct target *target)
2081 {
2082 int retval;
2083 if (target == NULL) {
2084 LOG_WARNING("No target has been configured");
2085 return ERROR_OK;
2086 }
2087
2088 if (target->state != TARGET_HALTED)
2089 return ERROR_OK;
2090
2091 retval = target->type->arch_state(target);
2092 return retval;
2093 }
2094
2095 static int target_get_gdb_fileio_info_default(struct target *target,
2096 struct gdb_fileio_info *fileio_info)
2097 {
2098 /* If target does not support semi-hosting function, target
2099 has no need to provide .get_gdb_fileio_info callback.
2100 It just return ERROR_FAIL and gdb_server will return "Txx"
2101 as target halted every time. */
2102 return ERROR_FAIL;
2103 }
2104
2105 static int target_gdb_fileio_end_default(struct target *target,
2106 int retcode, int fileio_errno, bool ctrl_c)
2107 {
2108 return ERROR_OK;
2109 }
2110
2111 static int target_profiling_default(struct target *target, uint32_t *samples,
2112 uint32_t max_num_samples, uint32_t *num_samples, uint32_t seconds)
2113 {
2114 struct timeval timeout, now;
2115
2116 gettimeofday(&timeout, NULL);
2117 timeval_add_time(&timeout, seconds, 0);
2118
2119 LOG_INFO("Starting profiling. Halting and resuming the"
2120 " target as often as we can...");
2121
2122 uint32_t sample_count = 0;
2123 /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2124 struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
2125
2126 int retval = ERROR_OK;
2127 for (;;) {
2128 target_poll(target);
2129 if (target->state == TARGET_HALTED) {
2130 uint32_t t = buf_get_u32(reg->value, 0, 32);
2131 samples[sample_count++] = t;
2132 /* current pc, addr = 0, do not handle breakpoints, not debugging */
2133 retval = target_resume(target, 1, 0, 0, 0);
2134 target_poll(target);
2135 alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2136 } else if (target->state == TARGET_RUNNING) {
2137 /* We want to quickly sample the PC. */
2138 retval = target_halt(target);
2139 } else {
2140 LOG_INFO("Target not halted or running");
2141 retval = ERROR_OK;
2142 break;
2143 }
2144
2145 if (retval != ERROR_OK)
2146 break;
2147
2148 gettimeofday(&now, NULL);
2149 if ((sample_count >= max_num_samples) || timeval_compare(&now, &timeout) >= 0) {
2150 LOG_INFO("Profiling completed. %" PRIu32 " samples.", sample_count);
2151 break;
2152 }
2153 }
2154
2155 *num_samples = sample_count;
2156 return retval;
2157 }
2158
2159 /* Single aligned words are guaranteed to use 16 or 32 bit access
2160 * mode respectively, otherwise data is handled as quickly as
2161 * possible
2162 */
2163 int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
2164 {
2165 LOG_DEBUG("writing buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2166 size, address);
2167
2168 if (!target_was_examined(target)) {
2169 LOG_ERROR("Target not examined yet");
2170 return ERROR_FAIL;
2171 }
2172
2173 if (size == 0)
2174 return ERROR_OK;
2175
2176 if ((address + size - 1) < address) {
2177 /* GDB can request this when e.g. PC is 0xfffffffc */
2178 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2179 address,
2180 size);
2181 return ERROR_FAIL;
2182 }
2183
2184 return target->type->write_buffer(target, address, size, buffer);
2185 }
2186
2187 static int target_write_buffer_default(struct target *target,
2188 target_addr_t address, uint32_t count, const uint8_t *buffer)
2189 {
2190 uint32_t size;
2191
2192 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2193 * will have something to do with the size we leave to it. */
2194 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2195 if (address & size) {
2196 int retval = target_write_memory(target, address, size, 1, buffer);
2197 if (retval != ERROR_OK)
2198 return retval;
2199 address += size;
2200 count -= size;
2201 buffer += size;
2202 }
2203 }
2204
2205 /* Write the data with as large access size as possible. */
2206 for (; size > 0; size /= 2) {
2207 uint32_t aligned = count - count % size;
2208 if (aligned > 0) {
2209 int retval = target_write_memory(target, address, size, aligned / size, buffer);
2210 if (retval != ERROR_OK)
2211 return retval;
2212 address += aligned;
2213 count -= aligned;
2214 buffer += aligned;
2215 }
2216 }
2217
2218 return ERROR_OK;
2219 }
2220
2221 /* Single aligned words are guaranteed to use 16 or 32 bit access
2222 * mode respectively, otherwise data is handled as quickly as
2223 * possible
2224 */
2225 int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
2226 {
2227 LOG_DEBUG("reading buffer of %" PRIi32 " byte at " TARGET_ADDR_FMT,
2228 size, address);
2229
2230 if (!target_was_examined(target)) {
2231 LOG_ERROR("Target not examined yet");
2232 return ERROR_FAIL;
2233 }
2234
2235 if (size == 0)
2236 return ERROR_OK;
2237
2238 if ((address + size - 1) < address) {
2239 /* GDB can request this when e.g. PC is 0xfffffffc */
2240 LOG_ERROR("address + size wrapped (" TARGET_ADDR_FMT ", 0x%08" PRIx32 ")",
2241 address,
2242 size);
2243 return ERROR_FAIL;
2244 }
2245
2246 return target->type->read_buffer(target, address, size, buffer);
2247 }
2248
2249 static int target_read_buffer_default(struct target *target, target_addr_t address, uint32_t count, uint8_t *buffer)
2250 {
2251 uint32_t size;
2252
2253 /* Align up to maximum 4 bytes. The loop condition makes sure the next pass
2254 * will have something to do with the size we leave to it. */
2255 for (size = 1; size < 4 && count >= size * 2 + (address & size); size *= 2) {
2256 if (address & size) {
2257 int retval = target_read_memory(target, address, size, 1, buffer);
2258 if (retval != ERROR_OK)
2259 return retval;
2260 address += size;
2261 count -= size;
2262 buffer += size;
2263 }
2264 }
2265
2266 /* Read the data with as large access size as possible. */
2267 for (; size > 0; size /= 2) {
2268 uint32_t aligned = count - count % size;
2269 if (aligned > 0) {
2270 int retval = target_read_memory(target, address, size, aligned / size, buffer);
2271 if (retval != ERROR_OK)
2272 return retval;
2273 address += aligned;
2274 count -= aligned;
2275 buffer += aligned;
2276 }
2277 }
2278
2279 return ERROR_OK;
2280 }
2281
2282 int target_checksum_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t* crc)
2283 {
2284 uint8_t *buffer;
2285 int retval;
2286 uint32_t i;
2287 uint32_t checksum = 0;
2288 if (!target_was_examined(target)) {
2289 LOG_ERROR("Target not examined yet");
2290 return ERROR_FAIL;
2291 }
2292
2293 retval = target->type->checksum_memory(target, address, size, &checksum);
2294 if (retval != ERROR_OK) {
2295 buffer = malloc(size);
2296 if (buffer == NULL) {
2297 LOG_ERROR("error allocating buffer for section (%" PRId32 " bytes)", size);
2298 return ERROR_COMMAND_SYNTAX_ERROR;
2299 }
2300 retval = target_read_buffer(target, address, size, buffer);
2301 if (retval != ERROR_OK) {
2302 free(buffer);
2303 return retval;
2304 }
2305
2306 /* convert to target endianness */
2307 for (i = 0; i < (size/sizeof(uint32_t)); i++) {
2308 uint32_t target_data;
2309 target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
2310 target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
2311 }
2312
2313 retval = image_calculate_checksum(buffer, size, &checksum);
2314 free(buffer);
2315 }
2316
2317 *crc = checksum;
2318
2319 return retval;
2320 }
2321
2322 int target_blank_check_memory(struct target *target,
2323 struct target_memory_check_block *blocks, int num_blocks,
2324 uint8_t erased_value)
2325 {
2326 if (!target_was_examined(target)) {
2327 LOG_ERROR("Target not examined yet");
2328 return ERROR_FAIL;
2329 }
2330
2331 if (target->type->blank_check_memory == NULL)
2332 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
2333
2334 return target->type->blank_check_memory(target, blocks, num_blocks, erased_value);
2335 }
2336
2337 int target_read_u64(struct target *target, target_addr_t address, uint64_t *value)
2338 {
2339 uint8_t value_buf[8];
2340 if (!target_was_examined(target)) {
2341 LOG_ERROR("Target not examined yet");
2342 return ERROR_FAIL;
2343 }
2344
2345 int retval = target_read_memory(target, address, 8, 1, value_buf);
2346
2347 if (retval == ERROR_OK) {
2348 *value = target_buffer_get_u64(target, value_buf);
2349 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2350 address,
2351 *value);
2352 } else {
2353 *value = 0x0;
2354 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2355 address);
2356 }
2357
2358 return retval;
2359 }
2360
2361 int target_read_u32(struct target *target, target_addr_t address, uint32_t *value)
2362 {
2363 uint8_t value_buf[4];
2364 if (!target_was_examined(target)) {
2365 LOG_ERROR("Target not examined yet");
2366 return ERROR_FAIL;
2367 }
2368
2369 int retval = target_read_memory(target, address, 4, 1, value_buf);
2370
2371 if (retval == ERROR_OK) {
2372 *value = target_buffer_get_u32(target, value_buf);
2373 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2374 address,
2375 *value);
2376 } else {
2377 *value = 0x0;
2378 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2379 address);
2380 }
2381
2382 return retval;
2383 }
2384
2385 int target_read_u16(struct target *target, target_addr_t address, uint16_t *value)
2386 {
2387 uint8_t value_buf[2];
2388 if (!target_was_examined(target)) {
2389 LOG_ERROR("Target not examined yet");
2390 return ERROR_FAIL;
2391 }
2392
2393 int retval = target_read_memory(target, address, 2, 1, value_buf);
2394
2395 if (retval == ERROR_OK) {
2396 *value = target_buffer_get_u16(target, value_buf);
2397 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%4.4" PRIx16,
2398 address,
2399 *value);
2400 } else {
2401 *value = 0x0;
2402 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2403 address);
2404 }
2405
2406 return retval;
2407 }
2408
2409 int target_read_u8(struct target *target, target_addr_t address, uint8_t *value)
2410 {
2411 if (!target_was_examined(target)) {
2412 LOG_ERROR("Target not examined yet");
2413 return ERROR_FAIL;
2414 }
2415
2416 int retval = target_read_memory(target, address, 1, 1, value);
2417
2418 if (retval == ERROR_OK) {
2419 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2420 address,
2421 *value);
2422 } else {
2423 *value = 0x0;
2424 LOG_DEBUG("address: " TARGET_ADDR_FMT " failed",
2425 address);
2426 }
2427
2428 return retval;
2429 }
2430
2431 int target_write_u64(struct target *target, target_addr_t address, uint64_t value)
2432 {
2433 int retval;
2434 uint8_t value_buf[8];
2435 if (!target_was_examined(target)) {
2436 LOG_ERROR("Target not examined yet");
2437 return ERROR_FAIL;
2438 }
2439
2440 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2441 address,
2442 value);
2443
2444 target_buffer_set_u64(target, value_buf, value);
2445 retval = target_write_memory(target, address, 8, 1, value_buf);
2446 if (retval != ERROR_OK)
2447 LOG_DEBUG("failed: %i", retval);
2448
2449 return retval;
2450 }
2451
2452 int target_write_u32(struct target *target, target_addr_t address, uint32_t value)
2453 {
2454 int retval;
2455 uint8_t value_buf[4];
2456 if (!target_was_examined(target)) {
2457 LOG_ERROR("Target not examined yet");
2458 return ERROR_FAIL;
2459 }
2460
2461 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2462 address,
2463 value);
2464
2465 target_buffer_set_u32(target, value_buf, value);
2466 retval = target_write_memory(target, address, 4, 1, value_buf);
2467 if (retval != ERROR_OK)
2468 LOG_DEBUG("failed: %i", retval);
2469
2470 return retval;
2471 }
2472
2473 int target_write_u16(struct target *target, target_addr_t address, uint16_t value)
2474 {
2475 int retval;
2476 uint8_t value_buf[2];
2477 if (!target_was_examined(target)) {
2478 LOG_ERROR("Target not examined yet");
2479 return ERROR_FAIL;
2480 }
2481
2482 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2483 address,
2484 value);
2485
2486 target_buffer_set_u16(target, value_buf, value);
2487 retval = target_write_memory(target, address, 2, 1, value_buf);
2488 if (retval != ERROR_OK)
2489 LOG_DEBUG("failed: %i", retval);
2490
2491 return retval;
2492 }
2493
2494 int target_write_u8(struct target *target, target_addr_t address, uint8_t value)
2495 {
2496 int retval;
2497 if (!target_was_examined(target)) {
2498 LOG_ERROR("Target not examined yet");
2499 return ERROR_FAIL;
2500 }
2501
2502 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2503 address, value);
2504
2505 retval = target_write_memory(target, address, 1, 1, &value);
2506 if (retval != ERROR_OK)
2507 LOG_DEBUG("failed: %i", retval);
2508
2509 return retval;
2510 }
2511
2512 int target_write_phys_u64(struct target *target, target_addr_t address, uint64_t value)
2513 {
2514 int retval;
2515 uint8_t value_buf[8];
2516 if (!target_was_examined(target)) {
2517 LOG_ERROR("Target not examined yet");
2518 return ERROR_FAIL;
2519 }
2520
2521 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%16.16" PRIx64 "",
2522 address,
2523 value);
2524
2525 target_buffer_set_u64(target, value_buf, value);
2526 retval = target_write_phys_memory(target, address, 8, 1, value_buf);
2527 if (retval != ERROR_OK)
2528 LOG_DEBUG("failed: %i", retval);
2529
2530 return retval;
2531 }
2532
2533 int target_write_phys_u32(struct target *target, target_addr_t address, uint32_t value)
2534 {
2535 int retval;
2536 uint8_t value_buf[4];
2537 if (!target_was_examined(target)) {
2538 LOG_ERROR("Target not examined yet");
2539 return ERROR_FAIL;
2540 }
2541
2542 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx32 "",
2543 address,
2544 value);
2545
2546 target_buffer_set_u32(target, value_buf, value);
2547 retval = target_write_phys_memory(target, address, 4, 1, value_buf);
2548 if (retval != ERROR_OK)
2549 LOG_DEBUG("failed: %i", retval);
2550
2551 return retval;
2552 }
2553
2554 int target_write_phys_u16(struct target *target, target_addr_t address, uint16_t value)
2555 {
2556 int retval;
2557 uint8_t value_buf[2];
2558 if (!target_was_examined(target)) {
2559 LOG_ERROR("Target not examined yet");
2560 return ERROR_FAIL;
2561 }
2562
2563 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%8.8" PRIx16,
2564 address,
2565 value);
2566
2567 target_buffer_set_u16(target, value_buf, value);
2568 retval = target_write_phys_memory(target, address, 2, 1, value_buf);
2569 if (retval != ERROR_OK)
2570 LOG_DEBUG("failed: %i", retval);
2571
2572 return retval;
2573 }
2574
2575 int target_write_phys_u8(struct target *target, target_addr_t address, uint8_t value)
2576 {
2577 int retval;
2578 if (!target_was_examined(target)) {
2579 LOG_ERROR("Target not examined yet");
2580 return ERROR_FAIL;
2581 }
2582
2583 LOG_DEBUG("address: " TARGET_ADDR_FMT ", value: 0x%2.2" PRIx8,
2584 address, value);
2585
2586 retval = target_write_phys_memory(target, address, 1, 1, &value);
2587 if (retval != ERROR_OK)
2588 LOG_DEBUG("failed: %i", retval);
2589
2590 return retval;
2591 }
2592
2593 static int find_target(struct command_invocation *cmd, const char *name)
2594 {
2595 struct target *target = get_target(name);
2596 if (target == NULL) {
2597 command_print(cmd, "Target: %s is unknown, try one of:\n", name);
2598 return ERROR_FAIL;
2599 }
2600 if (!target->tap->enabled) {
2601 command_print(cmd, "Target: TAP %s is disabled, "
2602 "can't be the current target\n",
2603 target->tap->dotted_name);
2604 return ERROR_FAIL;
2605 }
2606
2607 cmd->ctx->current_target = target;
2608 if (cmd->ctx->current_target_override)
2609 cmd->ctx->current_target_override = target;
2610
2611 return ERROR_OK;
2612 }
2613
2614
2615 COMMAND_HANDLER(handle_targets_command)
2616 {
2617 int retval = ERROR_OK;
2618 if (CMD_ARGC == 1) {
2619 retval = find_target(CMD, CMD_ARGV[0]);
2620 if (retval == ERROR_OK) {
2621 /* we're done! */
2622 return retval;
2623 }
2624 }
2625
2626 struct target *target = all_targets;
2627 command_print(CMD, " TargetName Type Endian TapName State ");
2628 command_print(CMD, "-- ------------------ ---------- ------ ------------------ ------------");
2629 while (target) {
2630 const char *state;
2631 char marker = ' ';
2632
2633 if (target->tap->enabled)
2634 state = target_state_name(target);
2635 else
2636 state = "tap-disabled";
2637
2638 if (CMD_CTX->current_target == target)
2639 marker = '*';
2640
2641 /* keep columns lined up to match the headers above */
2642 command_print(CMD,
2643 "%2d%c %-18s %-10s %-6s %-18s %s",
2644 target->target_number,
2645 marker,
2646 target_name(target),
2647 target_type_name(target),
2648 Jim_Nvp_value2name_simple(nvp_target_endian,
2649 target->endianness)->name,
2650 target->tap->dotted_name,
2651 state);
2652 target = target->next;
2653 }
2654
2655 return retval;
2656 }
2657
2658 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
2659
2660 static int powerDropout;
2661 static int srstAsserted;
2662
2663 static int runPowerRestore;
2664 static int runPowerDropout;
2665 static int runSrstAsserted;
2666 static int runSrstDeasserted;
2667
2668 static int sense_handler(void)
2669 {
2670 static int prevSrstAsserted;
2671 static int prevPowerdropout;
2672
2673 int retval = jtag_power_dropout(&powerDropout);
2674 if (retval != ERROR_OK)
2675 return retval;
2676
2677 int powerRestored;
2678 powerRestored = prevPowerdropout && !powerDropout;
2679 if (powerRestored)
2680 runPowerRestore = 1;
2681
2682 int64_t current = timeval_ms();
2683 static int64_t lastPower;
2684 bool waitMore = lastPower + 2000 > current;
2685 if (powerDropout && !waitMore) {
2686 runPowerDropout = 1;
2687 lastPower = current;
2688 }
2689
2690 retval = jtag_srst_asserted(&srstAsserted);
2691 if (retval != ERROR_OK)
2692 return retval;
2693
2694 int srstDeasserted;
2695 srstDeasserted = prevSrstAsserted && !srstAsserted;
2696
2697 static int64_t lastSrst;
2698 waitMore = lastSrst + 2000 > current;
2699 if (srstDeasserted && !waitMore) {
2700 runSrstDeasserted = 1;
2701 lastSrst = current;
2702 }
2703
2704 if (!prevSrstAsserted && srstAsserted)
2705 runSrstAsserted = 1;
2706
2707 prevSrstAsserted = srstAsserted;
2708 prevPowerdropout = powerDropout;
2709
2710 if (srstDeasserted || powerRestored) {
2711 /* Other than logging the event we can't do anything here.
2712 * Issuing a reset is a particularly bad idea as we might
2713 * be inside a reset already.
2714 */
2715 }
2716
2717 return ERROR_OK;
2718 }
2719
2720 /* process target state changes */
2721 static int handle_target(void *priv)
2722 {
2723 Jim_Interp *interp = (Jim_Interp *)priv;
2724 int retval = ERROR_OK;
2725
2726 if (!is_jtag_poll_safe()) {
2727 /* polling is disabled currently */
2728 return ERROR_OK;
2729 }
2730
2731 /* we do not want to recurse here... */
2732 static int recursive;
2733 if (!recursive) {
2734 recursive = 1;
2735 sense_handler();
2736 /* danger! running these procedures can trigger srst assertions and power dropouts.
2737 * We need to avoid an infinite loop/recursion here and we do that by
2738 * clearing the flags after running these events.
2739 */
2740 int did_something = 0;
2741 if (runSrstAsserted) {
2742 LOG_INFO("srst asserted detected, running srst_asserted proc.");
2743 Jim_Eval(interp, "srst_asserted");
2744 did_something = 1;
2745 }
2746 if (runSrstDeasserted) {
2747 Jim_Eval(interp, "srst_deasserted");
2748 did_something = 1;
2749 }
2750 if (runPowerDropout) {
2751 LOG_INFO("Power dropout detected, running power_dropout proc.");
2752 Jim_Eval(interp, "power_dropout");
2753 did_something = 1;
2754 }
2755 if (runPowerRestore) {
2756 Jim_Eval(interp, "power_restore");
2757 did_something = 1;
2758 }
2759
2760 if (did_something) {
2761 /* clear detect flags */
2762 sense_handler();
2763 }
2764
2765 /* clear action flags */
2766
2767 runSrstAsserted = 0;
2768 runSrstDeasserted = 0;
2769 runPowerRestore = 0;
2770 runPowerDropout = 0;
2771
2772 recursive = 0;
2773 }
2774
2775 /* Poll targets for state changes unless that's globally disabled.
2776 * Skip targets that are currently disabled.
2777 */
2778 for (struct target *target = all_targets;
2779 is_jtag_poll_safe() && target;
2780 target = target->next) {
2781
2782 if (!target_was_examined(target))
2783 continue;
2784
2785 if (!target->tap->enabled)
2786 continue;
2787
2788 if (target->backoff.times > target->backoff.count) {
2789 /* do not poll this time as we failed previously */
2790 target->backoff.count++;
2791 continue;
2792 }
2793 target->backoff.count = 0;
2794
2795 /* only poll target if we've got power and srst isn't asserted */
2796 if (!powerDropout && !srstAsserted) {
2797 /* polling may fail silently until the target has been examined */
2798 retval = target_poll(target);
2799 if (retval != ERROR_OK) {
2800 /* 100ms polling interval. Increase interval between polling up to 5000ms */
2801 if (target->backoff.times * polling_interval < 5000) {
2802 target->backoff.times *= 2;
2803 target->backoff.times++;
2804 }
2805
2806 /* Tell GDB to halt the debugger. This allows the user to
2807 * run monitor commands to handle the situation.
2808 */
2809 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
2810 }
2811 if (target->backoff.times > 0) {
2812 LOG_USER("Polling target %s failed, trying to reexamine", target_name(target));
2813 target_reset_examined(target);
2814 retval = target_examine_one(target);
2815 /* Target examination could have failed due to unstable connection,
2816 * but we set the examined flag anyway to repoll it later */
2817 if (retval != ERROR_OK) {
2818 target->examined = true;
2819 LOG_USER("Examination failed, GDB will be halted. Polling again in %dms",
2820 target->backoff.times * polling_interval);
2821 return retval;
2822 }
2823 }
2824
2825 /* Since we succeeded, we reset backoff count */
2826 target->backoff.times = 0;
2827 }
2828 }
2829
2830 return retval;
2831 }
2832
2833 COMMAND_HANDLER(handle_reg_command)
2834 {
2835 struct target *target;
2836 struct reg *reg = NULL;
2837 unsigned count = 0;
2838 char *value;
2839
2840 LOG_DEBUG("-");
2841
2842 target = get_current_target(CMD_CTX);
2843
2844 /* list all available registers for the current target */
2845 if (CMD_ARGC == 0) {
2846 struct reg_cache *cache = target->reg_cache;
2847
2848 count = 0;
2849 while (cache) {
2850 unsigned i;
2851
2852 command_print(CMD, "===== %s", cache->name);
2853
2854 for (i = 0, reg = cache->reg_list;
2855 i < cache->num_regs;
2856 i++, reg++, count++) {
2857 if (reg->exist == false)
2858 continue;
2859 /* only print cached values if they are valid */
2860 if (reg->valid) {
2861 value = buf_to_str(reg->value,
2862 reg->size, 16);
2863 command_print(CMD,
2864 "(%i) %s (/%" PRIu32 "): 0x%s%s",
2865 count, reg->name,
2866 reg->size, value,
2867 reg->dirty
2868 ? " (dirty)"
2869 : "");
2870 free(value);
2871 } else {
2872 command_print(CMD, "(%i) %s (/%" PRIu32 ")",
2873 count, reg->name,
2874 reg->size) ;
2875 }
2876 }
2877 cache = cache->next;
2878 }
2879
2880 return ERROR_OK;
2881 }
2882
2883 /* access a single register by its ordinal number */
2884 if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9')) {
2885 unsigned num;
2886 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2887
2888 struct reg_cache *cache = target->reg_cache;
2889 count = 0;
2890 while (cache) {
2891 unsigned i;
2892 for (i = 0; i < cache->num_regs; i++) {
2893 if (count++ == num) {
2894 reg = &cache->reg_list[i];
2895 break;
2896 }
2897 }
2898 if (reg)
2899 break;
2900 cache = cache->next;
2901 }
2902
2903 if (!reg) {
2904 command_print(CMD, "%i is out of bounds, the current target "
2905 "has only %i registers (0 - %i)", num, count, count - 1);
2906 return ERROR_OK;
2907 }
2908 } else {
2909 /* access a single register by its name */
2910 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2911
2912 if (!reg)
2913 goto not_found;
2914 }
2915
2916 assert(reg != NULL); /* give clang a hint that we *know* reg is != NULL here */
2917
2918 if (!reg->exist)
2919 goto not_found;
2920
2921 /* display a register */
2922 if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0')
2923 && (CMD_ARGV[1][0] <= '9')))) {
2924 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2925 reg->valid = 0;
2926
2927 if (reg->valid == 0)
2928 reg->type->get(reg);
2929 value = buf_to_str(reg->value, reg->size, 16);
2930 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2931 free(value);
2932 return ERROR_OK;
2933 }
2934
2935 /* set register value */
2936 if (CMD_ARGC == 2) {
2937 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2938 if (buf == NULL)
2939 return ERROR_FAIL;
2940 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2941
2942 reg->type->set(reg, buf);
2943
2944 value = buf_to_str(reg->value, reg->size, 16);
2945 command_print(CMD, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2946 free(value);
2947
2948 free(buf);
2949
2950 return ERROR_OK;
2951 }
2952
2953 return ERROR_COMMAND_SYNTAX_ERROR;
2954
2955 not_found:
2956 command_print(CMD, "register %s not found in current target", CMD_ARGV[0]);
2957 return ERROR_OK;
2958 }
2959
2960 COMMAND_HANDLER(handle_poll_command)
2961 {
2962 int retval = ERROR_OK;
2963 struct target *target = get_current_target(CMD_CTX);
2964
2965 if (CMD_ARGC == 0) {
2966 command_print(CMD, "background polling: %s",
2967 jtag_poll_get_enabled() ? "on" : "off");
2968 command_print(CMD, "TAP: %s (%s)",
2969 target->tap->dotted_name,
2970 target->tap->enabled ? "enabled" : "disabled");
2971 if (!target->tap->enabled)
2972 return ERROR_OK;
2973 retval = target_poll(target);
2974 if (retval != ERROR_OK)
2975 return retval;
2976 retval = target_arch_state(target);
2977 if (retval != ERROR_OK)
2978 return retval;
2979 } else if (CMD_ARGC == 1) {
2980 bool enable;
2981 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2982 jtag_poll_set_enabled(enable);
2983 } else
2984 return ERROR_COMMAND_SYNTAX_ERROR;
2985
2986 return retval;
2987 }
2988
2989 COMMAND_HANDLER(handle_wait_halt_command)
2990 {
2991 if (CMD_ARGC > 1)
2992 return ERROR_COMMAND_SYNTAX_ERROR;
2993
2994 unsigned ms = DEFAULT_HALT_TIMEOUT;
2995 if (1 == CMD_ARGC) {
2996 int retval = parse_uint(CMD_ARGV[0], &ms);
2997 if (ERROR_OK != retval)
2998 return ERROR_COMMAND_SYNTAX_ERROR;
2999 }
3000
3001 struct target *target = get_current_target(CMD_CTX);
3002 return target_wait_state(target, TARGET_HALTED, ms);
3003 }
3004
3005 /* wait for target state to change. The trick here is to have a low
3006 * latency for short waits and not to suck up all the CPU time
3007 * on longer waits.
3008 *
3009 * After 500ms, keep_alive() is invoked
3010 */
3011 int target_wait_state(struct target *target, enum target_state state, int ms)
3012 {
3013 int retval;
3014 int64_t then = 0, cur;
3015 bool once = true;
3016
3017 for (;;) {
3018 retval = target_poll(target);
3019 if (retval != ERROR_OK)
3020 return retval;
3021 if (target->state == state)
3022 break;
3023 cur = timeval_ms();
3024 if (once) {
3025 once = false;
3026 then = timeval_ms();
3027 LOG_DEBUG("waiting for target %s...",
3028 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
3029 }
3030
3031 if (cur-then > 500)
3032 keep_alive();
3033
3034 if ((cur-then) > ms) {
3035 LOG_ERROR("timed out while waiting for target %s",
3036 Jim_Nvp_value2name_simple(nvp_target_state, state)->name);
3037 return ERROR_FAIL;
3038 }
3039 }
3040
3041 return ERROR_OK;
3042 }
3043
3044 COMMAND_HANDLER(handle_halt_command)
3045 {
3046 LOG_DEBUG("-");
3047
3048 struct target *target = get_current_target(CMD_CTX);
3049
3050 target->verbose_halt_msg = true;
3051
3052 int retval = target_halt(target);
3053 if (ERROR_OK != retval)
3054 return retval;
3055
3056 if (CMD_ARGC == 1) {
3057 unsigned wait_local;
3058 retval = parse_uint(CMD_ARGV[0], &wait_local);
3059 if (ERROR_OK != retval)
3060 return ERROR_COMMAND_SYNTAX_ERROR;
3061 if (!wait_local)
3062 return ERROR_OK;
3063 }
3064
3065 return CALL_COMMAND_HANDLER(handle_wait_halt_command);
3066 }
3067
3068 COMMAND_HANDLER(handle_soft_reset_halt_command)
3069 {
3070 struct target *target = get_current_target(CMD_CTX);
3071
3072 LOG_USER("requesting target halt and executing a soft reset");
3073
3074 target_soft_reset_halt(target);
3075
3076 return ERROR_OK;
3077 }
3078
3079 COMMAND_HANDLER(handle_reset_command)
3080 {
3081 if (CMD_ARGC > 1)
3082 return ERROR_COMMAND_SYNTAX_ERROR;
3083
3084 enum target_reset_mode reset_mode = RESET_RUN;
3085 if (CMD_ARGC == 1) {
3086 const Jim_Nvp *n;
3087 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
3088 if ((n->name == NULL) || (n->value == RESET_UNKNOWN))
3089 return ERROR_COMMAND_SYNTAX_ERROR;
3090 reset_mode = n->value;
3091 }
3092
3093 /* reset *all* targets */
3094 return target_process_reset(CMD, reset_mode);
3095 }
3096
3097
3098 COMMAND_HANDLER(handle_resume_command)
3099 {
3100 int current = 1;
3101 if (CMD_ARGC > 1)
3102 return ERROR_COMMAND_SYNTAX_ERROR;
3103
3104 struct target *target = get_current_target(CMD_CTX);
3105
3106 /* with no CMD_ARGV, resume from current pc, addr = 0,
3107 * with one arguments, addr = CMD_ARGV[0],
3108 * handle breakpoints, not debugging */
3109 target_addr_t addr = 0;
3110 if (CMD_ARGC == 1) {
3111 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3112 current = 0;
3113 }
3114
3115 return target_resume(target, current, addr, 1, 0);
3116 }
3117
3118 COMMAND_HANDLER(handle_step_command)
3119 {
3120 if (CMD_ARGC > 1)
3121 return ERROR_COMMAND_SYNTAX_ERROR;
3122
3123 LOG_DEBUG("-");
3124
3125 /* with no CMD_ARGV, step from current pc, addr = 0,
3126 * with one argument addr = CMD_ARGV[0],
3127 * handle breakpoints, debugging */
3128 target_addr_t addr = 0;
3129 int current_pc = 1;
3130 if (CMD_ARGC == 1) {
3131 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3132 current_pc = 0;
3133 }
3134
3135 struct target *target = get_current_target(CMD_CTX);
3136
3137 return target->type->step(target, current_pc, addr, 1);
3138 }
3139
3140 void target_handle_md_output(struct command_invocation *cmd,
3141 struct target *target, target_addr_t address, unsigned size,
3142 unsigned count, const uint8_t *buffer)
3143 {
3144 const unsigned line_bytecnt = 32;
3145 unsigned line_modulo = line_bytecnt / size;
3146
3147 char output[line_bytecnt * 4 + 1];
3148 unsigned output_len = 0;
3149
3150 const char *value_fmt;
3151 switch (size) {
3152 case 8:
3153 value_fmt = "%16.16"PRIx64" ";
3154 break;
3155 case 4:
3156 value_fmt = "%8.8"PRIx64" ";
3157 break;
3158 case 2:
3159 value_fmt = "%4.4"PRIx64" ";
3160 break;
3161 case 1:
3162 value_fmt = "%2.2"PRIx64" ";
3163 break;
3164 default:
3165 /* "can't happen", caller checked */
3166 LOG_ERROR("invalid memory read size: %u", size);
3167 return;
3168 }
3169
3170 for (unsigned i = 0; i < count; i++) {
3171 if (i % line_modulo == 0) {
3172 output_len += snprintf(output + output_len,
3173 sizeof(output) - output_len,
3174 TARGET_ADDR_FMT ": ",
3175 (address + (i * size)));
3176 }
3177
3178 uint64_t value = 0;
3179 const uint8_t *value_ptr = buffer + i * size;
3180 switch (size) {
3181 case 8:
3182 value = target_buffer_get_u64(target, value_ptr);
3183 break;
3184 case 4:
3185 value = target_buffer_get_u32(target, value_ptr);
3186 break;
3187 case 2:
3188 value = target_buffer_get_u16(target, value_ptr);
3189 break;
3190 case 1:
3191 value = *value_ptr;
3192 }
3193 output_len += snprintf(output + output_len,
3194 sizeof(output) - output_len,
3195 value_fmt, value);
3196
3197 if ((i % line_modulo == line_modulo - 1) || (i == count - 1)) {
3198 command_print(cmd, "%s", output);
3199 output_len = 0;
3200 }
3201 }
3202 }
3203
3204 COMMAND_HANDLER(handle_md_command)
3205 {
3206 if (CMD_ARGC < 1)
3207 return ERROR_COMMAND_SYNTAX_ERROR;
3208
3209 unsigned size = 0;
3210 switch (CMD_NAME[2]) {
3211 case 'd':
3212 size = 8;
3213 break;
3214 case 'w':
3215 size = 4;
3216 break;
3217 case 'h':
3218 size = 2;
3219 break;
3220 case 'b':
3221 size = 1;
3222 break;
3223 default:
3224 return ERROR_COMMAND_SYNTAX_ERROR;
3225 }
3226
3227 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3228 int (*fn)(struct target *target,
3229 target_addr_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
3230 if (physical) {
3231 CMD_ARGC--;
3232 CMD_ARGV++;
3233 fn = target_read_phys_memory;
3234 } else
3235 fn = target_read_memory;
3236 if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
3237 return ERROR_COMMAND_SYNTAX_ERROR;
3238
3239 target_addr_t address;
3240 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3241
3242 unsigned count = 1;
3243 if (CMD_ARGC == 2)
3244 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
3245
3246 uint8_t *buffer = calloc(count, size);
3247 if (buffer == NULL) {
3248 LOG_ERROR("Failed to allocate md read buffer");
3249 return ERROR_FAIL;
3250 }
3251
3252 struct target *target = get_current_target(CMD_CTX);
3253 int retval = fn(target, address, size, count, buffer);
3254 if (ERROR_OK == retval)
3255 target_handle_md_output(CMD, target, address, size, count, buffer);
3256
3257 free(buffer);
3258
3259 return retval;
3260 }
3261
3262 typedef int (*target_write_fn)(struct target *target,
3263 target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
3264
3265 static int target_fill_mem(struct target *target,
3266 target_addr_t address,
3267 target_write_fn fn,
3268 unsigned data_size,
3269 /* value */
3270 uint64_t b,
3271 /* count */
3272 unsigned c)
3273 {
3274 /* We have to write in reasonably large chunks to be able
3275 * to fill large memory areas with any sane speed */
3276 const unsigned chunk_size = 16384;
3277 uint8_t *target_buf = malloc(chunk_size * data_size);
3278 if (target_buf == NULL) {
3279 LOG_ERROR("Out of memory");
3280 return ERROR_FAIL;
3281 }
3282
3283 for (unsigned i = 0; i < chunk_size; i++) {
3284 switch (data_size) {
3285 case 8:
3286 target_buffer_set_u64(target, target_buf + i * data_size, b);
3287 break;
3288 case 4:
3289 target_buffer_set_u32(target, target_buf + i * data_size, b);
3290 break;
3291 case 2:
3292 target_buffer_set_u16(target, target_buf + i * data_size, b);
3293 break;
3294 case 1:
3295 target_buffer_set_u8(target, target_buf + i * data_size, b);
3296 break;
3297 default:
3298 exit(-1);
3299 }
3300 }
3301
3302 int retval = ERROR_OK;
3303
3304 for (unsigned x = 0; x < c; x += chunk_size) {
3305 unsigned current;
3306 current = c - x;
3307 if (current > chunk_size)
3308 current = chunk_size;
3309 retval = fn(target, address + x * data_size, data_size, current, target_buf);
3310 if (retval != ERROR_OK)
3311 break;
3312 /* avoid GDB timeouts */
3313 keep_alive();
3314 }
3315 free(target_buf);
3316
3317 return retval;
3318 }
3319
3320
3321 COMMAND_HANDLER(handle_mw_command)
3322 {
3323 if (CMD_ARGC < 2)
3324 return ERROR_COMMAND_SYNTAX_ERROR;
3325 bool physical = strcmp(CMD_ARGV[0], "phys") == 0;
3326 target_write_fn fn;
3327 if (physical) {
3328 CMD_ARGC--;
3329 CMD_ARGV++;
3330 fn = target_write_phys_memory;
3331 } else
3332 fn = target_write_memory;
3333 if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
3334 return ERROR_COMMAND_SYNTAX_ERROR;
3335
3336 target_addr_t address;
3337 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
3338
3339 target_addr_t value;
3340 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], value);
3341
3342 unsigned count = 1;
3343 if (CMD_ARGC == 3)
3344 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
3345
3346 struct target *target = get_current_target(CMD_CTX);
3347 unsigned wordsize;
3348 switch (CMD_NAME[2]) {
3349 case 'd':
3350 wordsize = 8;
3351 break;
3352 case 'w':
3353 wordsize = 4;
3354 break;
3355 case 'h':
3356 wordsize = 2;
3357 break;
3358 case 'b':
3359 wordsize = 1;
3360 break;
3361 default:
3362 return ERROR_COMMAND_SYNTAX_ERROR;
3363 }
3364
3365 return target_fill_mem(target, address, fn, wordsize, value, count);
3366 }
3367
3368 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
3369 target_addr_t *min_address, target_addr_t *max_address)
3370 {
3371 if (CMD_ARGC < 1 || CMD_ARGC > 5)
3372 return ERROR_COMMAND_SYNTAX_ERROR;
3373
3374 /* a base address isn't always necessary,
3375 * default to 0x0 (i.e. don't relocate) */
3376 if (CMD_ARGC >= 2) {
3377 target_addr_t addr;
3378 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3379 image->base_address = addr;
3380 image->base_address_set = 1;
3381 } else
3382 image->base_address_set = 0;
3383
3384 image->start_address_set = 0;
3385
3386 if (CMD_ARGC >= 4)
3387 COMMAND_PARSE_ADDRESS(CMD_ARGV[3], *min_address);
3388 if (CMD_ARGC == 5) {
3389 COMMAND_PARSE_ADDRESS(CMD_ARGV[4], *max_address);
3390 /* use size (given) to find max (required) */
3391 *max_address += *min_address;
3392 }
3393
3394 if (*min_address > *max_address)
3395 return ERROR_COMMAND_SYNTAX_ERROR;
3396
3397 return ERROR_OK;
3398 }
3399
3400 COMMAND_HANDLER(handle_load_image_command)
3401 {
3402 uint8_t *buffer;
3403 size_t buf_cnt;
3404 uint32_t image_size;
3405 target_addr_t min_address = 0;
3406 target_addr_t max_address = -1;
3407 int i;
3408 struct image image;
3409
3410 int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
3411 &image, &min_address, &max_address);
3412 if (ERROR_OK != retval)
3413 return retval;
3414
3415 struct target *target = get_current_target(CMD_CTX);
3416
3417 struct duration bench;
3418 duration_start(&bench);
3419
3420 if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
3421 return ERROR_FAIL;
3422
3423 image_size = 0x0;
3424 retval = ERROR_OK;
3425 for (i = 0; i < image.num_sections; i++) {
3426 buffer = malloc(image.sections[i].size);
3427 if (buffer == NULL) {
3428 command_print(CMD,
3429 "error allocating buffer for section (%d bytes)",
3430 (int)(image.sections[i].size));
3431 retval = ERROR_FAIL;
3432 break;
3433 }
3434
3435 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3436 if (retval != ERROR_OK) {
3437 free(buffer);
3438 break;
3439 }
3440
3441 uint32_t offset = 0;
3442 uint32_t length = buf_cnt;
3443
3444 /* DANGER!!! beware of unsigned comparision here!!! */
3445
3446 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
3447 (image.sections[i].base_address < max_address)) {
3448
3449 if (image.sections[i].base_address < min_address) {
3450 /* clip addresses below */
3451 offset += min_address-image.sections[i].base_address;
3452 length -= offset;
3453 }
3454
3455 if (image.sections[i].base_address + buf_cnt > max_address)
3456 length -= (image.sections[i].base_address + buf_cnt)-max_address;
3457
3458 retval = target_write_buffer(target,
3459 image.sections[i].base_address + offset, length, buffer + offset);
3460 if (retval != ERROR_OK) {
3461 free(buffer);
3462 break;
3463 }
3464 image_size += length;
3465 command_print(CMD, "%u bytes written at address " TARGET_ADDR_FMT "",
3466 (unsigned int)length,
3467 image.sections[i].base_address + offset);
3468 }
3469
3470 free(buffer);
3471 }
3472
3473 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3474 command_print(CMD, "downloaded %" PRIu32 " bytes "
3475 "in %fs (%0.3f KiB/s)", image_size,
3476 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3477 }
3478
3479 image_close(&image);
3480
3481 return retval;
3482
3483 }
3484
3485 COMMAND_HANDLER(handle_dump_image_command)
3486 {
3487 struct fileio *fileio;
3488 uint8_t *buffer;
3489 int retval, retvaltemp;
3490 target_addr_t address, size;
3491 struct duration bench;
3492 struct target *target = get_current_target(CMD_CTX);
3493
3494 if (CMD_ARGC != 3)
3495 return ERROR_COMMAND_SYNTAX_ERROR;
3496
3497 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], address);
3498 COMMAND_PARSE_ADDRESS(CMD_ARGV[2], size);
3499
3500 uint32_t buf_size = (size > 4096) ? 4096 : size;
3501 buffer = malloc(buf_size);
3502 if (!buffer)
3503 return ERROR_FAIL;
3504
3505 retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
3506 if (retval != ERROR_OK) {
3507 free(buffer);
3508 return retval;
3509 }
3510
3511 duration_start(&bench);
3512
3513 while (size > 0) {
3514 size_t size_written;
3515 uint32_t this_run_size = (size > buf_size) ? buf_size : size;
3516 retval = target_read_buffer(target, address, this_run_size, buffer);
3517 if (retval != ERROR_OK)
3518 break;
3519
3520 retval = fileio_write(fileio, this_run_size, buffer, &size_written);
3521 if (retval != ERROR_OK)
3522 break;
3523
3524 size -= this_run_size;
3525 address += this_run_size;
3526 }
3527
3528 free(buffer);
3529
3530 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3531 size_t filesize;
3532 retval = fileio_size(fileio, &filesize);
3533 if (retval != ERROR_OK)
3534 return retval;
3535 command_print(CMD,
3536 "dumped %zu bytes in %fs (%0.3f KiB/s)", filesize,
3537 duration_elapsed(&bench), duration_kbps(&bench, filesize));
3538 }
3539
3540 retvaltemp = fileio_close(fileio);
3541 if (retvaltemp != ERROR_OK)
3542 return retvaltemp;
3543
3544 return retval;
3545 }
3546
3547 enum verify_mode {
3548 IMAGE_TEST = 0,
3549 IMAGE_VERIFY = 1,
3550 IMAGE_CHECKSUM_ONLY = 2
3551 };
3552
3553 static COMMAND_HELPER(handle_verify_image_command_internal, enum verify_mode verify)
3554 {
3555 uint8_t *buffer;
3556 size_t buf_cnt;
3557 uint32_t image_size;
3558 int i;
3559 int retval;
3560 uint32_t checksum = 0;
3561 uint32_t mem_checksum = 0;
3562
3563 struct image image;
3564
3565 struct target *target = get_current_target(CMD_CTX);
3566
3567 if (CMD_ARGC < 1)
3568 return ERROR_COMMAND_SYNTAX_ERROR;
3569
3570 if (!target) {
3571 LOG_ERROR("no target selected");
3572 return ERROR_FAIL;
3573 }
3574
3575 struct duration bench;
3576 duration_start(&bench);
3577
3578 if (CMD_ARGC >= 2) {
3579 target_addr_t addr;
3580 COMMAND_PARSE_ADDRESS(CMD_ARGV[1], addr);
3581 image.base_address = addr;
3582 image.base_address_set = 1;
3583 } else {
3584 image.base_address_set = 0;
3585 image.base_address = 0x0;
3586 }
3587
3588 image.start_address_set = 0;
3589
3590 retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
3591 if (retval != ERROR_OK)
3592 return retval;
3593
3594 image_size = 0x0;
3595 int diffs = 0;
3596 retval = ERROR_OK;
3597 for (i = 0; i < image.num_sections; i++) {
3598 buffer = malloc(image.sections[i].size);
3599 if (buffer == NULL) {
3600 command_print(CMD,
3601 "error allocating buffer for section (%d bytes)",
3602 (int)(image.sections[i].size));
3603 break;
3604 }
3605 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
3606 if (retval != ERROR_OK) {
3607 free(buffer);
3608 break;
3609 }
3610
3611 if (verify >= IMAGE_VERIFY) {
3612 /* calculate checksum of image */
3613 retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
3614 if (retval != ERROR_OK) {
3615 free(buffer);
3616 break;
3617 }
3618
3619 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
3620 if (retval != ERROR_OK) {
3621 free(buffer);
3622 break;
3623 }
3624 if ((checksum != mem_checksum) && (verify == IMAGE_CHECKSUM_ONLY)) {
3625 LOG_ERROR("checksum mismatch");
3626 free(buffer);
3627 retval = ERROR_FAIL;
3628 goto done;
3629 }
3630 if (checksum != mem_checksum) {
3631 /* failed crc checksum, fall back to a binary compare */
3632 uint8_t *data;
3633
3634 if (diffs == 0)
3635 LOG_ERROR("checksum mismatch - attempting binary compare");
3636
3637 data = malloc(buf_cnt);
3638
3639 /* Can we use 32bit word accesses? */
3640 int size = 1;
3641 int count = buf_cnt;
3642 if ((count % 4) == 0) {
3643 size *= 4;
3644 count /= 4;
3645 }
3646 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3647 if (retval == ERROR_OK) {
3648 uint32_t t;
3649 for (t = 0; t < buf_cnt; t++) {
3650 if (data[t] != buffer[t]) {
3651 command_print(CMD,
3652 "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3653 diffs,
3654 (unsigned)(t + image.sections[i].base_address),
3655 data[t],
3656 buffer[t]);
3657 if (diffs++ >= 127) {
3658 command_print(CMD, "More than 128 errors, the rest are not printed.");
3659 free(data);
3660 free(buffer);
3661 goto done;
3662 }
3663 }
3664 keep_alive();
3665 }
3666 }
3667 free(data);
3668 }
3669 } else {
3670 command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3671 image.sections[i].base_address,
3672 buf_cnt);
3673 }
3674
3675 free(buffer);
3676 image_size += buf_cnt;
3677 }
3678 if (diffs > 0)
3679 command_print(CMD, "No more differences found.");
3680 done:
3681 if (diffs > 0)
3682 retval = ERROR_FAIL;
3683 if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3684 command_print(CMD, "verified %" PRIu32 " bytes "
3685 "in %fs (%0.3f KiB/s)", image_size,
3686 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3687 }
3688