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