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