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