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