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