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