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