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