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