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