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