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