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