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