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