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