dsp5680xx: disable for now, it generates warnings
[fw/openocd] / src / target / target.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007-2010 Ã˜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  *   Copyright (C) 2011 by Broadcom Corporation                            *
18  *   Evan Hunter - ehunter@broadcom.com                                    *
19  *                                                                         *
20  *   Copyright (C) ST-Ericsson SA 2011                                     *
21  *   michel.jaouen@stericsson.com : smp minimum support                    *
22  *                                                                         *
23  *   This program is free software; you can redistribute it and/or modify  *
24  *   it under the terms of the GNU General Public License as published by  *
25  *   the Free Software Foundation; either version 2 of the License, or     *
26  *   (at your option) any later version.                                   *
27  *                                                                         *
28  *   This program is distributed in the hope that it will be useful,       *
29  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
30  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
31  *   GNU General Public License for more details.                          *
32  *                                                                         *
33  *   You should have received a copy of the GNU General Public License     *
34  *   along with this program; if not, write to the                         *
35  *   Free Software Foundation, Inc.,                                       *
36  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
37  ***************************************************************************/
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
41
42 #include <helper/time_support.h>
43 #include <jtag/jtag.h>
44 #include <flash/nor/core.h>
45
46 #include "target.h"
47 #include "target_type.h"
48 #include "target_request.h"
49 #include "breakpoints.h"
50 #include "register.h"
51 #include "trace.h"
52 #include "image.h"
53 #include "rtos/rtos.h"
54
55
56 static int target_read_buffer_default(struct target *target, uint32_t address,
57                 uint32_t size, uint8_t *buffer);
58 static int target_write_buffer_default(struct target *target, uint32_t address,
59                 uint32_t size, const uint8_t *buffer);
60 static int target_array2mem(Jim_Interp *interp, struct target *target,
61                 int argc, Jim_Obj *const *argv);
62 static int target_mem2array(Jim_Interp *interp, struct target *target,
63                 int argc, Jim_Obj *const *argv);
64 static int target_register_user_commands(struct command_context *cmd_ctx);
65
66 /* targets */
67 extern struct target_type arm7tdmi_target;
68 extern struct target_type arm720t_target;
69 extern struct target_type arm9tdmi_target;
70 extern struct target_type arm920t_target;
71 extern struct target_type arm966e_target;
72 extern struct target_type arm946e_target;
73 extern struct target_type arm926ejs_target;
74 extern struct target_type fa526_target;
75 extern struct target_type feroceon_target;
76 extern struct target_type dragonite_target;
77 extern struct target_type xscale_target;
78 extern struct target_type cortexm3_target;
79 extern struct target_type cortexa8_target;
80 extern struct target_type arm11_target;
81 extern struct target_type mips_m4k_target;
82 extern struct target_type avr_target;
83 extern struct target_type dsp563xx_target;
84 //extern struct target_type dsp5680xx_target;
85 extern struct target_type testee_target;
86 extern struct target_type avr32_ap7k_target;
87
88 static struct target_type *target_types[] =
89 {
90         &arm7tdmi_target,
91         &arm9tdmi_target,
92         &arm920t_target,
93         &arm720t_target,
94         &arm966e_target,
95         &arm946e_target,
96         &arm926ejs_target,
97         &fa526_target,
98         &feroceon_target,
99         &dragonite_target,
100         &xscale_target,
101         &cortexm3_target,
102         &cortexa8_target,
103         &arm11_target,
104         &mips_m4k_target,
105         &avr_target,
106         &dsp563xx_target,
107 // Disabled for now, it generates warnings
108 //      &dsp5680xx_target,
109         &testee_target,
110         &avr32_ap7k_target,
111         NULL,
112 };
113
114 struct target *all_targets = NULL;
115 static struct target_event_callback *target_event_callbacks = NULL;
116 static struct target_timer_callback *target_timer_callbacks = NULL;
117 static const int polling_interval = 100;
118
119 static const Jim_Nvp nvp_assert[] = {
120         { .name = "assert", NVP_ASSERT },
121         { .name = "deassert", NVP_DEASSERT },
122         { .name = "T", NVP_ASSERT },
123         { .name = "F", NVP_DEASSERT },
124         { .name = "t", NVP_ASSERT },
125         { .name = "f", NVP_DEASSERT },
126         { .name = NULL, .value = -1 }
127 };
128
129 static const Jim_Nvp nvp_error_target[] = {
130         { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
131         { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
132         { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
133         { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
134         { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
135         { .value = ERROR_TARGET_UNALIGNED_ACCESS   , .name = "err-unaligned-access" },
136         { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
137         { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
138         { .value = ERROR_TARGET_TRANSLATION_FAULT  , .name = "err-translation-fault" },
139         { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
140         { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
141         { .value = -1, .name = NULL }
142 };
143
144 static const char *target_strerror_safe(int err)
145 {
146         const Jim_Nvp *n;
147
148         n = Jim_Nvp_value2name_simple(nvp_error_target, err);
149         if (n->name == NULL) {
150                 return "unknown";
151         } else {
152                 return n->name;
153         }
154 }
155
156 static const Jim_Nvp nvp_target_event[] = {
157         { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
158         { .value = TARGET_EVENT_OLD_pre_resume         , .name = "old-pre_resume" },
159
160         { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
161         { .value = TARGET_EVENT_HALTED, .name = "halted" },
162         { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
163         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
164         { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
165
166         { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
167         { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
168
169         /* historical name */
170
171         { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
172
173         { .value = TARGET_EVENT_RESET_ASSERT_PRE,    .name = "reset-assert-pre" },
174         { .value = TARGET_EVENT_RESET_ASSERT,        .name = "reset-assert" },
175         { .value = TARGET_EVENT_RESET_ASSERT_POST,   .name = "reset-assert-post" },
176         { .value = TARGET_EVENT_RESET_DEASSERT_PRE,  .name = "reset-deassert-pre" },
177         { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
178         { .value = TARGET_EVENT_RESET_HALT_PRE,      .name = "reset-halt-pre" },
179         { .value = TARGET_EVENT_RESET_HALT_POST,     .name = "reset-halt-post" },
180         { .value = TARGET_EVENT_RESET_WAIT_PRE,      .name = "reset-wait-pre" },
181         { .value = TARGET_EVENT_RESET_WAIT_POST,     .name = "reset-wait-post" },
182         { .value = TARGET_EVENT_RESET_INIT,          .name = "reset-init" },
183         { .value = TARGET_EVENT_RESET_END,           .name = "reset-end" },
184
185         { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
186         { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
187
188         { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
189         { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
190
191         { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
192         { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
193
194         { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
195         { .value = TARGET_EVENT_GDB_FLASH_WRITE_END  , .name = "gdb-flash-write-end"   },
196
197         { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
198         { .value = TARGET_EVENT_GDB_FLASH_ERASE_END  , .name = "gdb-flash-erase-end" },
199
200         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
201         { .value = TARGET_EVENT_RESUMED     , .name = "resume-ok" },
202         { .value = TARGET_EVENT_RESUME_END  , .name = "resume-end" },
203
204         { .name = NULL, .value = -1 }
205 };
206
207 static const Jim_Nvp nvp_target_state[] = {
208         { .name = "unknown", .value = TARGET_UNKNOWN },
209         { .name = "running", .value = TARGET_RUNNING },
210         { .name = "halted",  .value = TARGET_HALTED },
211         { .name = "reset",   .value = TARGET_RESET },
212         { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
213         { .name = NULL, .value = -1 },
214 };
215
216 static const Jim_Nvp nvp_target_debug_reason [] = {
217         { .name = "debug-request"            , .value = DBG_REASON_DBGRQ },
218         { .name = "breakpoint"               , .value = DBG_REASON_BREAKPOINT },
219         { .name = "watchpoint"               , .value = DBG_REASON_WATCHPOINT },
220         { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
221         { .name = "single-step"              , .value = DBG_REASON_SINGLESTEP },
222         { .name = "target-not-halted"        , .value = DBG_REASON_NOTHALTED  },
223         { .name = "undefined"                , .value = DBG_REASON_UNDEFINED },
224         { .name = NULL, .value = -1 },
225 };
226
227 static const Jim_Nvp nvp_target_endian[] = {
228         { .name = "big",    .value = TARGET_BIG_ENDIAN },
229         { .name = "little", .value = TARGET_LITTLE_ENDIAN },
230         { .name = "be",     .value = TARGET_BIG_ENDIAN },
231         { .name = "le",     .value = TARGET_LITTLE_ENDIAN },
232         { .name = NULL,     .value = -1 },
233 };
234
235 static const Jim_Nvp nvp_reset_modes[] = {
236         { .name = "unknown", .value = RESET_UNKNOWN },
237         { .name = "run"    , .value = RESET_RUN },
238         { .name = "halt"   , .value = RESET_HALT },
239         { .name = "init"   , .value = RESET_INIT },
240         { .name = NULL     , .value = -1 },
241 };
242
243 const char *debug_reason_name(struct target *t)
244 {
245         const char *cp;
246
247         cp = Jim_Nvp_value2name_simple(nvp_target_debug_reason,
248                         t->debug_reason)->name;
249         if (!cp) {
250                 LOG_ERROR("Invalid debug reason: %d", (int)(t->debug_reason));
251                 cp = "(*BUG*unknown*BUG*)";
252         }
253         return cp;
254 }
255
256 const char *
257 target_state_name( struct target *t )
258 {
259         const char *cp;
260         cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
261         if( !cp ){
262                 LOG_ERROR("Invalid target state: %d", (int)(t->state));
263                 cp = "(*BUG*unknown*BUG*)";
264         }
265         return cp;
266 }
267
268 /* determine the number of the new target */
269 static int new_target_number(void)
270 {
271         struct target *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 /* read a uint32_t from a buffer in target memory endianness */
287 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
288 {
289         if (target->endianness == TARGET_LITTLE_ENDIAN)
290                 return le_to_h_u32(buffer);
291         else
292                 return be_to_h_u32(buffer);
293 }
294
295 /* read a uint24_t from a buffer in target memory endianness */
296 uint32_t target_buffer_get_u24(struct target *target, const uint8_t *buffer)
297 {
298         if (target->endianness == TARGET_LITTLE_ENDIAN)
299                 return le_to_h_u24(buffer);
300         else
301                 return be_to_h_u24(buffer);
302 }
303
304 /* read a uint16_t from a buffer in target memory endianness */
305 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
306 {
307         if (target->endianness == TARGET_LITTLE_ENDIAN)
308                 return le_to_h_u16(buffer);
309         else
310                 return be_to_h_u16(buffer);
311 }
312
313 /* read a uint8_t from a buffer in target memory endianness */
314 static uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
315 {
316         return *buffer & 0x0ff;
317 }
318
319 /* write a uint32_t to a buffer in target memory endianness */
320 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
321 {
322         if (target->endianness == TARGET_LITTLE_ENDIAN)
323                 h_u32_to_le(buffer, value);
324         else
325                 h_u32_to_be(buffer, value);
326 }
327
328 /* write a uint24_t to a buffer in target memory endianness */
329 void target_buffer_set_u24(struct target *target, uint8_t *buffer, uint32_t value)
330 {
331         if (target->endianness == TARGET_LITTLE_ENDIAN)
332                 h_u24_to_le(buffer, value);
333         else
334                 h_u24_to_be(buffer, value);
335 }
336
337 /* write a uint16_t to a buffer in target memory endianness */
338 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
339 {
340         if (target->endianness == TARGET_LITTLE_ENDIAN)
341                 h_u16_to_le(buffer, value);
342         else
343                 h_u16_to_be(buffer, value);
344 }
345
346 /* write a uint8_t to a buffer in target memory endianness */
347 static void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
348 {
349         *buffer = value;
350 }
351
352 /* return a pointer to a configured target; id is name or number */
353 struct target *get_target(const char *id)
354 {
355         struct target *target;
356
357         /* try as tcltarget name */
358         for (target = all_targets; target; target = target->next) {
359                 if (target->cmd_name == NULL)
360                         continue;
361                 if (strcmp(id, target->cmd_name) == 0)
362                         return target;
363         }
364
365         /* It's OK to remove this fallback sometime after August 2010 or so */
366
367         /* no match, try as number */
368         unsigned num;
369         if (parse_uint(id, &num) != ERROR_OK)
370                 return NULL;
371
372         for (target = all_targets; target; target = target->next) {
373                 if (target->target_number == (int)num) {
374                         LOG_WARNING("use '%s' as target identifier, not '%u'",
375                                         target->cmd_name, num);
376                         return target;
377                 }
378         }
379
380         return NULL;
381 }
382
383 /* returns a pointer to the n-th configured target */
384 static struct target *get_target_by_num(int num)
385 {
386         struct target *target = all_targets;
387
388         while (target) {
389                 if (target->target_number == num) {
390                         return target;
391                 }
392                 target = target->next;
393         }
394
395         return NULL;
396 }
397
398 struct target* get_current_target(struct command_context *cmd_ctx)
399 {
400         struct target *target = get_target_by_num(cmd_ctx->current_target);
401
402         if (target == NULL)
403         {
404                 LOG_ERROR("BUG: current_target out of bounds");
405                 exit(-1);
406         }
407
408         return target;
409 }
410
411 int target_poll(struct target *target)
412 {
413         int retval;
414
415         /* We can't poll until after examine */
416         if (!target_was_examined(target))
417         {
418                 /* Fail silently lest we pollute the log */
419                 return ERROR_FAIL;
420         }
421
422         retval = target->type->poll(target);
423         if (retval != ERROR_OK)
424                 return retval;
425
426         if (target->halt_issued)
427         {
428                 if (target->state == TARGET_HALTED)
429                 {
430                         target->halt_issued = false;
431                 } else
432                 {
433                         long long t = timeval_ms() - target->halt_issued_time;
434                         if (t>1000)
435                         {
436                                 target->halt_issued = false;
437                                 LOG_INFO("Halt timed out, wake up GDB.");
438                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
439                         }
440                 }
441         }
442
443         return ERROR_OK;
444 }
445
446 int target_halt(struct target *target)
447 {
448         int retval;
449         /* We can't poll until after examine */
450         if (!target_was_examined(target))
451         {
452                 LOG_ERROR("Target not examined yet");
453                 return ERROR_FAIL;
454         }
455
456         retval = target->type->halt(target);
457         if (retval != ERROR_OK)
458                 return retval;
459
460         target->halt_issued = true;
461         target->halt_issued_time = timeval_ms();
462
463         return ERROR_OK;
464 }
465
466 /**
467  * Make the target (re)start executing using its saved execution
468  * context (possibly with some modifications).
469  *
470  * @param target Which target should start executing.
471  * @param current True to use the target's saved program counter instead
472  *      of the address parameter
473  * @param address Optionally used as the program counter.
474  * @param handle_breakpoints True iff breakpoints at the resumption PC
475  *      should be skipped.  (For example, maybe execution was stopped by
476  *      such a breakpoint, in which case it would be counterprodutive to
477  *      let it re-trigger.
478  * @param debug_execution False if all working areas allocated by OpenOCD
479  *      should be released and/or restored to their original contents.
480  *      (This would for example be true to run some downloaded "helper"
481  *      algorithm code, which resides in one such working buffer and uses
482  *      another for data storage.)
483  *
484  * @todo Resolve the ambiguity about what the "debug_execution" flag
485  * signifies.  For example, Target implementations don't agree on how
486  * it relates to invalidation of the register cache, or to whether
487  * breakpoints and watchpoints should be enabled.  (It would seem wrong
488  * to enable breakpoints when running downloaded "helper" algorithms
489  * (debug_execution true), since the breakpoints would be set to match
490  * target firmware being debugged, not the helper algorithm.... and
491  * enabling them could cause such helpers to malfunction (for example,
492  * by overwriting data with a breakpoint instruction.  On the other
493  * hand the infrastructure for running such helpers might use this
494  * procedure but rely on hardware breakpoint to detect termination.)
495  */
496 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
497 {
498         int retval;
499
500         /* We can't poll until after examine */
501         if (!target_was_examined(target))
502         {
503                 LOG_ERROR("Target not examined yet");
504                 return ERROR_FAIL;
505         }
506
507         /* note that resume *must* be asynchronous. The CPU can halt before
508          * we poll. The CPU can even halt at the current PC as a result of
509          * a software breakpoint being inserted by (a bug?) the application.
510          */
511         if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
512                 return retval;
513
514         return retval;
515 }
516
517 static int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
518 {
519         char buf[100];
520         int retval;
521         Jim_Nvp *n;
522         n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
523         if (n->name == NULL) {
524                 LOG_ERROR("invalid reset mode");
525                 return ERROR_FAIL;
526         }
527
528         /* disable polling during reset to make reset event scripts
529          * more predictable, i.e. dr/irscan & pathmove in events will
530          * not have JTAG operations injected into the middle of a sequence.
531          */
532         bool save_poll = jtag_poll_get_enabled();
533
534         jtag_poll_set_enabled(false);
535
536         sprintf(buf, "ocd_process_reset %s", n->name);
537         retval = Jim_Eval(cmd_ctx->interp, buf);
538
539         jtag_poll_set_enabled(save_poll);
540
541         if (retval != JIM_OK) {
542                 Jim_MakeErrorMessage(cmd_ctx->interp);
543                 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(cmd_ctx->interp), NULL));
544                 return ERROR_FAIL;
545         }
546
547         /* We want any events to be processed before the prompt */
548         retval = target_call_timer_callbacks_now();
549
550         struct target *target;
551         for (target = all_targets; target; target = target->next) {
552                 target->type->check_reset(target);
553         }
554
555         return retval;
556 }
557
558 static int identity_virt2phys(struct target *target,
559                 uint32_t virtual, uint32_t *physical)
560 {
561         *physical = virtual;
562         return ERROR_OK;
563 }
564
565 static int no_mmu(struct target *target, int *enabled)
566 {
567         *enabled = 0;
568         return ERROR_OK;
569 }
570
571 static int default_examine(struct target *target)
572 {
573         target_set_examined(target);
574         return ERROR_OK;
575 }
576
577 /* no check by default */
578 static int default_check_reset(struct target *target)
579 {
580         return ERROR_OK;
581 }
582
583 int target_examine_one(struct target *target)
584 {
585         return target->type->examine(target);
586 }
587
588 static int jtag_enable_callback(enum jtag_event event, void *priv)
589 {
590         struct target *target = priv;
591
592         if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
593                 return ERROR_OK;
594
595         jtag_unregister_event_callback(jtag_enable_callback, target);
596         return target_examine_one(target);
597 }
598
599
600 /* Targets that correctly implement init + examine, i.e.
601  * no communication with target during init:
602  *
603  * XScale
604  */
605 int target_examine(void)
606 {
607         int retval = ERROR_OK;
608         struct target *target;
609
610         for (target = all_targets; target; target = target->next)
611         {
612                 /* defer examination, but don't skip it */
613                 if (!target->tap->enabled) {
614                         jtag_register_event_callback(jtag_enable_callback,
615                                         target);
616                         continue;
617                 }
618                 if ((retval = target_examine_one(target)) != ERROR_OK)
619                         return retval;
620         }
621         return retval;
622 }
623 const char *target_type_name(struct target *target)
624 {
625         return target->type->name;
626 }
627
628 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
629 {
630         if (!target_was_examined(target))
631         {
632                 LOG_ERROR("Target not examined yet");
633                 return ERROR_FAIL;
634         }
635         return target->type->write_memory_imp(target, address, size, count, buffer);
636 }
637
638 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
639 {
640         if (!target_was_examined(target))
641         {
642                 LOG_ERROR("Target not examined yet");
643                 return ERROR_FAIL;
644         }
645         return target->type->read_memory_imp(target, address, size, count, buffer);
646 }
647
648 static int target_soft_reset_halt_imp(struct target *target)
649 {
650         if (!target_was_examined(target))
651         {
652                 LOG_ERROR("Target not examined yet");
653                 return ERROR_FAIL;
654         }
655         if (!target->type->soft_reset_halt_imp) {
656                 LOG_ERROR("Target %s does not support soft_reset_halt",
657                                 target_name(target));
658                 return ERROR_FAIL;
659         }
660         return target->type->soft_reset_halt_imp(target);
661 }
662
663 /**
664  * Downloads a target-specific native code algorithm to the target,
665  * and executes it.  * Note that some targets may need to set up, enable,
666  * and tear down a breakpoint (hard or * soft) to detect algorithm
667  * termination, while others may support  lower overhead schemes where
668  * soft breakpoints embedded in the algorithm automatically terminate the
669  * algorithm.
670  *
671  * @param target used to run the algorithm
672  * @param arch_info target-specific description of the algorithm.
673  */
674 int target_run_algorithm(struct target *target,
675                 int num_mem_params, struct mem_param *mem_params,
676                 int num_reg_params, struct reg_param *reg_param,
677                 uint32_t entry_point, uint32_t exit_point,
678                 int timeout_ms, void *arch_info)
679 {
680         int retval = ERROR_FAIL;
681
682         if (!target_was_examined(target))
683         {
684                 LOG_ERROR("Target not examined yet");
685                 goto done;
686         }
687         if (!target->type->run_algorithm) {
688                 LOG_ERROR("Target type '%s' does not support %s",
689                                 target_type_name(target), __func__);
690                 goto done;
691         }
692
693         target->running_alg = true;
694         retval = target->type->run_algorithm(target,
695                         num_mem_params, mem_params,
696                         num_reg_params, reg_param,
697                         entry_point, exit_point, timeout_ms, arch_info);
698         target->running_alg = false;
699
700 done:
701         return retval;
702 }
703
704
705 int target_read_memory(struct target *target,
706                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
707 {
708         return target->type->read_memory(target, address, size, count, buffer);
709 }
710
711 static int target_read_phys_memory(struct target *target,
712                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
713 {
714         return target->type->read_phys_memory(target, address, size, count, buffer);
715 }
716
717 int target_write_memory(struct target *target,
718                 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
719 {
720         return target->type->write_memory(target, address, size, count, buffer);
721 }
722
723 static int target_write_phys_memory(struct target *target,
724                 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
725 {
726         return target->type->write_phys_memory(target, address, size, count, buffer);
727 }
728
729 int target_bulk_write_memory(struct target *target,
730                 uint32_t address, uint32_t count, const uint8_t *buffer)
731 {
732         return target->type->bulk_write_memory(target, address, count, buffer);
733 }
734
735 int target_add_breakpoint(struct target *target,
736                 struct breakpoint *breakpoint)
737 {
738         if ((target->state != TARGET_HALTED)&&(breakpoint->type!=BKPT_HARD)) {
739                 LOG_WARNING("target %s is not halted", target->cmd_name);
740                 return ERROR_TARGET_NOT_HALTED;
741         }
742         return target->type->add_breakpoint(target, breakpoint);
743 }
744 int target_remove_breakpoint(struct target *target,
745                 struct breakpoint *breakpoint)
746 {
747         return target->type->remove_breakpoint(target, breakpoint);
748 }
749
750 int target_add_watchpoint(struct target *target,
751                 struct watchpoint *watchpoint)
752 {
753         if (target->state != TARGET_HALTED) {
754                 LOG_WARNING("target %s is not halted", target->cmd_name);
755                 return ERROR_TARGET_NOT_HALTED;
756         }
757         return target->type->add_watchpoint(target, watchpoint);
758 }
759 int target_remove_watchpoint(struct target *target,
760                 struct watchpoint *watchpoint)
761 {
762         return target->type->remove_watchpoint(target, watchpoint);
763 }
764
765 int target_get_gdb_reg_list(struct target *target,
766                 struct reg **reg_list[], int *reg_list_size)
767 {
768         return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
769 }
770 int target_step(struct target *target,
771                 int current, uint32_t address, int handle_breakpoints)
772 {
773         return target->type->step(target, current, address, handle_breakpoints);
774 }
775
776
777 /**
778  * Reset the @c examined flag for the given target.
779  * Pure paranoia -- targets are zeroed on allocation.
780  */
781 static void target_reset_examined(struct target *target)
782 {
783         target->examined = false;
784 }
785
786 static int
787 err_read_phys_memory(struct target *target, uint32_t address,
788                 uint32_t size, uint32_t count, uint8_t *buffer)
789 {
790         LOG_ERROR("Not implemented: %s", __func__);
791         return ERROR_FAIL;
792 }
793
794 static int
795 err_write_phys_memory(struct target *target, uint32_t address,
796                 uint32_t size, uint32_t count, const uint8_t *buffer)
797 {
798         LOG_ERROR("Not implemented: %s", __func__);
799         return ERROR_FAIL;
800 }
801
802 static int handle_target(void *priv);
803
804 static int target_init_one(struct command_context *cmd_ctx,
805                 struct target *target)
806 {
807         target_reset_examined(target);
808
809         struct target_type *type = target->type;
810         if (type->examine == NULL)
811                 type->examine = default_examine;
812
813         if (type->check_reset== NULL)
814                 type->check_reset = default_check_reset;
815
816         int retval = type->init_target(cmd_ctx, target);
817         if (ERROR_OK != retval)
818         {
819                 LOG_ERROR("target '%s' init failed", target_name(target));
820                 return retval;
821         }
822
823         /**
824          * @todo get rid of those *memory_imp() methods, now that all
825          * callers are using target_*_memory() accessors ... and make
826          * sure the "physical" paths handle the same issues.
827          */
828         /* a non-invasive way(in terms of patches) to add some code that
829          * runs before the type->write/read_memory implementation
830          */
831         type->write_memory_imp = target->type->write_memory;
832         type->write_memory = target_write_memory_imp;
833
834         type->read_memory_imp = target->type->read_memory;
835         type->read_memory = target_read_memory_imp;
836
837         type->soft_reset_halt_imp = target->type->soft_reset_halt;
838         type->soft_reset_halt = target_soft_reset_halt_imp;
839
840         /* Sanity-check MMU support ... stub in what we must, to help
841          * implement it in stages, but warn if we need to do so.
842          */
843         if (type->mmu)
844         {
845                 if (type->write_phys_memory == NULL)
846                 {
847                         LOG_ERROR("type '%s' is missing write_phys_memory",
848                                         type->name);
849                         type->write_phys_memory = err_write_phys_memory;
850                 }
851                 if (type->read_phys_memory == NULL)
852                 {
853                         LOG_ERROR("type '%s' is missing read_phys_memory",
854                                         type->name);
855                         type->read_phys_memory = err_read_phys_memory;
856                 }
857                 if (type->virt2phys == NULL)
858                 {
859                         LOG_ERROR("type '%s' is missing virt2phys", type->name);
860                         type->virt2phys = identity_virt2phys;
861                 }
862         }
863         else
864         {
865                 /* Make sure no-MMU targets all behave the same:  make no
866                  * distinction between physical and virtual addresses, and
867                  * ensure that virt2phys() is always an identity mapping.
868                  */
869                 if (type->write_phys_memory || type->read_phys_memory
870                                 || type->virt2phys)
871                 {
872                         LOG_WARNING("type '%s' has bad MMU hooks", type->name);
873                 }
874
875                 type->mmu = no_mmu;
876                 type->write_phys_memory = type->write_memory;
877                 type->read_phys_memory = type->read_memory;
878                 type->virt2phys = identity_virt2phys;
879         }
880
881         if (target->type->read_buffer == NULL)
882                 target->type->read_buffer = target_read_buffer_default;
883
884         if (target->type->write_buffer == NULL)
885                 target->type->write_buffer = target_write_buffer_default;
886
887         return ERROR_OK;
888 }
889
890 static int target_init(struct command_context *cmd_ctx)
891 {
892         struct target *target;
893         int retval;
894
895         for (target = all_targets; target; target = target->next)
896         {
897                 retval = target_init_one(cmd_ctx, target);
898                 if (ERROR_OK != retval)
899                         return retval;
900         }
901
902         if (!all_targets)
903                 return ERROR_OK;
904
905         retval = target_register_user_commands(cmd_ctx);
906         if (ERROR_OK != retval)
907                 return retval;
908
909         retval = target_register_timer_callback(&handle_target,
910                         polling_interval, 1, cmd_ctx->interp);
911         if (ERROR_OK != retval)
912                 return retval;
913
914         return ERROR_OK;
915 }
916
917 COMMAND_HANDLER(handle_target_init_command)
918 {
919         if (CMD_ARGC != 0)
920                 return ERROR_COMMAND_SYNTAX_ERROR;
921
922         static bool target_initialized = false;
923         if (target_initialized)
924         {
925                 LOG_INFO("'target init' has already been called");
926                 return ERROR_OK;
927         }
928         target_initialized = true;
929
930         LOG_DEBUG("Initializing targets...");
931         return target_init(CMD_CTX);
932 }
933
934 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
935 {
936         struct target_event_callback **callbacks_p = &target_event_callbacks;
937
938         if (callback == NULL)
939         {
940                 return ERROR_INVALID_ARGUMENTS;
941         }
942
943         if (*callbacks_p)
944         {
945                 while ((*callbacks_p)->next)
946                         callbacks_p = &((*callbacks_p)->next);
947                 callbacks_p = &((*callbacks_p)->next);
948         }
949
950         (*callbacks_p) = malloc(sizeof(struct target_event_callback));
951         (*callbacks_p)->callback = callback;
952         (*callbacks_p)->priv = priv;
953         (*callbacks_p)->next = NULL;
954
955         return ERROR_OK;
956 }
957
958 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
959 {
960         struct target_timer_callback **callbacks_p = &target_timer_callbacks;
961         struct timeval now;
962
963         if (callback == NULL)
964         {
965                 return ERROR_INVALID_ARGUMENTS;
966         }
967
968         if (*callbacks_p)
969         {
970                 while ((*callbacks_p)->next)
971                         callbacks_p = &((*callbacks_p)->next);
972                 callbacks_p = &((*callbacks_p)->next);
973         }
974
975         (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
976         (*callbacks_p)->callback = callback;
977         (*callbacks_p)->periodic = periodic;
978         (*callbacks_p)->time_ms = time_ms;
979
980         gettimeofday(&now, NULL);
981         (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
982         time_ms -= (time_ms % 1000);
983         (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
984         if ((*callbacks_p)->when.tv_usec > 1000000)
985         {
986                 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
987                 (*callbacks_p)->when.tv_sec += 1;
988         }
989
990         (*callbacks_p)->priv = priv;
991         (*callbacks_p)->next = NULL;
992
993         return ERROR_OK;
994 }
995
996 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
997 {
998         struct target_event_callback **p = &target_event_callbacks;
999         struct target_event_callback *c = target_event_callbacks;
1000
1001         if (callback == NULL)
1002         {
1003                 return ERROR_INVALID_ARGUMENTS;
1004         }
1005
1006         while (c)
1007         {
1008                 struct target_event_callback *next = c->next;
1009                 if ((c->callback == callback) && (c->priv == priv))
1010                 {
1011                         *p = next;
1012                         free(c);
1013                         return ERROR_OK;
1014                 }
1015                 else
1016                         p = &(c->next);
1017                 c = next;
1018         }
1019
1020         return ERROR_OK;
1021 }
1022
1023 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
1024 {
1025         struct target_timer_callback **p = &target_timer_callbacks;
1026         struct target_timer_callback *c = target_timer_callbacks;
1027
1028         if (callback == NULL)
1029         {
1030                 return ERROR_INVALID_ARGUMENTS;
1031         }
1032
1033         while (c)
1034         {
1035                 struct target_timer_callback *next = c->next;
1036                 if ((c->callback == callback) && (c->priv == priv))
1037                 {
1038                         *p = next;
1039                         free(c);
1040                         return ERROR_OK;
1041                 }
1042                 else
1043                         p = &(c->next);
1044                 c = next;
1045         }
1046
1047         return ERROR_OK;
1048 }
1049
1050 int target_call_event_callbacks(struct target *target, enum target_event event)
1051 {
1052         struct target_event_callback *callback = target_event_callbacks;
1053         struct target_event_callback *next_callback;
1054
1055         if (event == TARGET_EVENT_HALTED)
1056         {
1057                 /* execute early halted first */
1058                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1059         }
1060
1061         LOG_DEBUG("target event %i (%s)",
1062                           event,
1063                           Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1064
1065         target_handle_event(target, event);
1066
1067         while (callback)
1068         {
1069                 next_callback = callback->next;
1070                 callback->callback(target, event, callback->priv);
1071                 callback = next_callback;
1072         }
1073
1074         return ERROR_OK;
1075 }
1076
1077 static int target_timer_callback_periodic_restart(
1078                 struct target_timer_callback *cb, struct timeval *now)
1079 {
1080         int time_ms = cb->time_ms;
1081         cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1082         time_ms -= (time_ms % 1000);
1083         cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1084         if (cb->when.tv_usec > 1000000)
1085         {
1086                 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1087                 cb->when.tv_sec += 1;
1088         }
1089         return ERROR_OK;
1090 }
1091
1092 static int target_call_timer_callback(struct target_timer_callback *cb,
1093                 struct timeval *now)
1094 {
1095         cb->callback(cb->priv);
1096
1097         if (cb->periodic)
1098                 return target_timer_callback_periodic_restart(cb, now);
1099
1100         return target_unregister_timer_callback(cb->callback, cb->priv);
1101 }
1102
1103 static int target_call_timer_callbacks_check_time(int checktime)
1104 {
1105         keep_alive();
1106
1107         struct timeval now;
1108         gettimeofday(&now, NULL);
1109
1110         struct target_timer_callback *callback = target_timer_callbacks;
1111         while (callback)
1112         {
1113                 // cleaning up may unregister and free this callback
1114                 struct target_timer_callback *next_callback = callback->next;
1115
1116                 bool call_it = callback->callback &&
1117                         ((!checktime && callback->periodic) ||
1118                           now.tv_sec > callback->when.tv_sec ||
1119                          (now.tv_sec == callback->when.tv_sec &&
1120                           now.tv_usec >= callback->when.tv_usec));
1121
1122                 if (call_it)
1123                 {
1124                         int retval = target_call_timer_callback(callback, &now);
1125                         if (retval != ERROR_OK)
1126                                 return retval;
1127                 }
1128
1129                 callback = next_callback;
1130         }
1131
1132         return ERROR_OK;
1133 }
1134
1135 int target_call_timer_callbacks(void)
1136 {
1137         return target_call_timer_callbacks_check_time(1);
1138 }
1139
1140 /* invoke periodic callbacks immediately */
1141 int target_call_timer_callbacks_now(void)
1142 {
1143         return target_call_timer_callbacks_check_time(0);
1144 }
1145
1146 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1147 {
1148         struct working_area *c = target->working_areas;
1149         struct working_area *new_wa = NULL;
1150
1151         /* Reevaluate working area address based on MMU state*/
1152         if (target->working_areas == NULL)
1153         {
1154                 int retval;
1155                 int enabled;
1156
1157                 retval = target->type->mmu(target, &enabled);
1158                 if (retval != ERROR_OK)
1159                 {
1160                         return retval;
1161                 }
1162
1163                 if (!enabled) {
1164                         if (target->working_area_phys_spec) {
1165                                 LOG_DEBUG("MMU disabled, using physical "
1166                                         "address for working memory 0x%08x",
1167                                         (unsigned)target->working_area_phys);
1168                                 target->working_area = target->working_area_phys;
1169                         } else {
1170                                 LOG_ERROR("No working memory available. "
1171                                         "Specify -work-area-phys to target.");
1172                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1173                         }
1174                 } else {
1175                         if (target->working_area_virt_spec) {
1176                                 LOG_DEBUG("MMU enabled, using virtual "
1177                                         "address for working memory 0x%08x",
1178                                         (unsigned)target->working_area_virt);
1179                                 target->working_area = target->working_area_virt;
1180                         } else {
1181                                 LOG_ERROR("No working memory available. "
1182                                         "Specify -work-area-virt to target.");
1183                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1184                         }
1185                 }
1186         }
1187
1188         /* only allocate multiples of 4 byte */
1189         if (size % 4)
1190         {
1191                 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1192                 size = (size + 3) & (~3);
1193         }
1194
1195         /* see if there's already a matching working area */
1196         while (c)
1197         {
1198                 if ((c->free) && (c->size == size))
1199                 {
1200                         new_wa = c;
1201                         break;
1202                 }
1203                 c = c->next;
1204         }
1205
1206         /* if not, allocate a new one */
1207         if (!new_wa)
1208         {
1209                 struct working_area **p = &target->working_areas;
1210                 uint32_t first_free = target->working_area;
1211                 uint32_t free_size = target->working_area_size;
1212
1213                 c = target->working_areas;
1214                 while (c)
1215                 {
1216                         first_free += c->size;
1217                         free_size -= c->size;
1218                         p = &c->next;
1219                         c = c->next;
1220                 }
1221
1222                 if (free_size < size)
1223                 {
1224                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1225                 }
1226
1227                 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1228
1229                 new_wa = malloc(sizeof(struct working_area));
1230                 new_wa->next = NULL;
1231                 new_wa->size = size;
1232                 new_wa->address = first_free;
1233
1234                 if (target->backup_working_area)
1235                 {
1236                         int retval;
1237                         new_wa->backup = malloc(new_wa->size);
1238                         if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1239                         {
1240                                 free(new_wa->backup);
1241                                 free(new_wa);
1242                                 return retval;
1243                         }
1244                 }
1245                 else
1246                 {
1247                         new_wa->backup = NULL;
1248                 }
1249
1250                 /* put new entry in list */
1251                 *p = new_wa;
1252         }
1253
1254         /* mark as used, and return the new (reused) area */
1255         new_wa->free = false;
1256         *area = new_wa;
1257
1258         /* user pointer */
1259         new_wa->user = area;
1260
1261         return ERROR_OK;
1262 }
1263
1264 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1265 {
1266         int retval;
1267
1268         retval = target_alloc_working_area_try(target, size, area);
1269         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1270         {
1271                 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1272         }
1273         return retval;
1274
1275 }
1276
1277 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1278 {
1279         if (area->free)
1280                 return ERROR_OK;
1281
1282         if (restore && target->backup_working_area)
1283         {
1284                 int retval;
1285                 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1286                         return retval;
1287         }
1288
1289         area->free = true;
1290
1291         /* mark user pointer invalid */
1292         *area->user = NULL;
1293         area->user = NULL;
1294
1295         return ERROR_OK;
1296 }
1297
1298 int target_free_working_area(struct target *target, struct working_area *area)
1299 {
1300         return target_free_working_area_restore(target, area, 1);
1301 }
1302
1303 /* free resources and restore memory, if restoring memory fails,
1304  * free up resources anyway
1305  */
1306 static void target_free_all_working_areas_restore(struct target *target, int restore)
1307 {
1308         struct working_area *c = target->working_areas;
1309
1310         while (c)
1311         {
1312                 struct working_area *next = c->next;
1313                 target_free_working_area_restore(target, c, restore);
1314
1315                 if (c->backup)
1316                         free(c->backup);
1317
1318                 free(c);
1319
1320                 c = next;
1321         }
1322
1323         target->working_areas = NULL;
1324 }
1325
1326 void target_free_all_working_areas(struct target *target)
1327 {
1328         target_free_all_working_areas_restore(target, 1);
1329 }
1330
1331 int target_arch_state(struct target *target)
1332 {
1333         int retval;
1334         if (target == NULL)
1335         {
1336                 LOG_USER("No target has been configured");
1337                 return ERROR_OK;
1338         }
1339
1340         LOG_USER("target state: %s", target_state_name( target ));
1341
1342         if (target->state != TARGET_HALTED)
1343                 return ERROR_OK;
1344
1345         retval = target->type->arch_state(target);
1346         return retval;
1347 }
1348
1349 /* Single aligned words are guaranteed to use 16 or 32 bit access
1350  * mode respectively, otherwise data is handled as quickly as
1351  * possible
1352  */
1353 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1354 {
1355         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1356                   (int)size, (unsigned)address);
1357
1358         if (!target_was_examined(target))
1359         {
1360                 LOG_ERROR("Target not examined yet");
1361                 return ERROR_FAIL;
1362         }
1363
1364         if (size == 0) {
1365                 return ERROR_OK;
1366         }
1367
1368         if ((address + size - 1) < address)
1369         {
1370                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1371                 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1372                                   (unsigned)address,
1373                                   (unsigned)size);
1374                 return ERROR_FAIL;
1375         }
1376
1377         return target->type->write_buffer(target, address, size, buffer);
1378 }
1379
1380 static int target_write_buffer_default(struct target *target, uint32_t address, uint32_t size, const uint8_t *buffer)
1381 {
1382         int retval = ERROR_OK;
1383
1384         if (((address % 2) == 0) && (size == 2))
1385         {
1386                 return target_write_memory(target, address, 2, 1, buffer);
1387         }
1388
1389         /* handle unaligned head bytes */
1390         if (address % 4)
1391         {
1392                 uint32_t unaligned = 4 - (address % 4);
1393
1394                 if (unaligned > size)
1395                         unaligned = size;
1396
1397                 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1398                         return retval;
1399
1400                 buffer += unaligned;
1401                 address += unaligned;
1402                 size -= unaligned;
1403         }
1404
1405         /* handle aligned words */
1406         if (size >= 4)
1407         {
1408                 int aligned = size - (size % 4);
1409
1410                 /* use bulk writes above a certain limit. This may have to be changed */
1411                 if (aligned > 128)
1412                 {
1413                         if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1414                                 return retval;
1415                 }
1416                 else
1417                 {
1418                         if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1419                                 return retval;
1420                 }
1421
1422                 buffer += aligned;
1423                 address += aligned;
1424                 size -= aligned;
1425         }
1426
1427         /* handle tail writes of less than 4 bytes */
1428         if (size > 0)
1429         {
1430                 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1431                         return retval;
1432         }
1433
1434         return retval;
1435 }
1436
1437 /* Single aligned words are guaranteed to use 16 or 32 bit access
1438  * mode respectively, otherwise data is handled as quickly as
1439  * possible
1440  */
1441 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1442 {
1443         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1444                           (int)size, (unsigned)address);
1445
1446         if (!target_was_examined(target))
1447         {
1448                 LOG_ERROR("Target not examined yet");
1449                 return ERROR_FAIL;
1450         }
1451
1452         if (size == 0) {
1453                 return ERROR_OK;
1454         }
1455
1456         if ((address + size - 1) < address)
1457         {
1458                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1459                 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1460                                   address,
1461                                   size);
1462                 return ERROR_FAIL;
1463         }
1464
1465         return target->type->read_buffer(target, address, size, buffer);
1466 }
1467
1468 static int target_read_buffer_default(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1469 {
1470         int retval = ERROR_OK;
1471
1472         if (((address % 2) == 0) && (size == 2))
1473         {
1474                 return target_read_memory(target, address, 2, 1, buffer);
1475         }
1476
1477         /* handle unaligned head bytes */
1478         if (address % 4)
1479         {
1480                 uint32_t unaligned = 4 - (address % 4);
1481
1482                 if (unaligned > size)
1483                         unaligned = size;
1484
1485                 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1486                         return retval;
1487
1488                 buffer += unaligned;
1489                 address += unaligned;
1490                 size -= unaligned;
1491         }
1492
1493         /* handle aligned words */
1494         if (size >= 4)
1495         {
1496                 int aligned = size - (size % 4);
1497
1498                 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1499                         return retval;
1500
1501                 buffer += aligned;
1502                 address += aligned;
1503                 size -= aligned;
1504         }
1505
1506         /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1507         if(size >=2)
1508         {
1509                 int aligned = size - (size%2);
1510                 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1511                 if (retval != ERROR_OK)
1512                         return retval;
1513
1514                 buffer += aligned;
1515                 address += aligned;
1516                 size -= aligned;
1517         }
1518         /* handle tail writes of less than 4 bytes */
1519         if (size > 0)
1520         {
1521                 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1522                         return retval;
1523         }
1524
1525         return ERROR_OK;
1526 }
1527
1528 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1529 {
1530         uint8_t *buffer;
1531         int retval;
1532         uint32_t i;
1533         uint32_t checksum = 0;
1534         if (!target_was_examined(target))
1535         {
1536                 LOG_ERROR("Target not examined yet");
1537                 return ERROR_FAIL;
1538         }
1539
1540         if ((retval = target->type->checksum_memory(target, address,
1541                 size, &checksum)) != ERROR_OK)
1542         {
1543                 buffer = malloc(size);
1544                 if (buffer == NULL)
1545                 {
1546                         LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1547                         return ERROR_INVALID_ARGUMENTS;
1548                 }
1549                 retval = target_read_buffer(target, address, size, buffer);
1550                 if (retval != ERROR_OK)
1551                 {
1552                         free(buffer);
1553                         return retval;
1554                 }
1555
1556                 /* convert to target endianness */
1557                 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1558                 {
1559                         uint32_t target_data;
1560                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1561                         target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1562                 }
1563
1564                 retval = image_calculate_checksum(buffer, size, &checksum);
1565                 free(buffer);
1566         }
1567
1568         *crc = checksum;
1569
1570         return retval;
1571 }
1572
1573 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1574 {
1575         int retval;
1576         if (!target_was_examined(target))
1577         {
1578                 LOG_ERROR("Target not examined yet");
1579                 return ERROR_FAIL;
1580         }
1581
1582         if (target->type->blank_check_memory == 0)
1583                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1584
1585         retval = target->type->blank_check_memory(target, address, size, blank);
1586
1587         return retval;
1588 }
1589
1590 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1591 {
1592         uint8_t value_buf[4];
1593         if (!target_was_examined(target))
1594         {
1595                 LOG_ERROR("Target not examined yet");
1596                 return ERROR_FAIL;
1597         }
1598
1599         int retval = target_read_memory(target, address, 4, 1, value_buf);
1600
1601         if (retval == ERROR_OK)
1602         {
1603                 *value = target_buffer_get_u32(target, value_buf);
1604                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1605                                   address,
1606                                   *value);
1607         }
1608         else
1609         {
1610                 *value = 0x0;
1611                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1612                                   address);
1613         }
1614
1615         return retval;
1616 }
1617
1618 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1619 {
1620         uint8_t value_buf[2];
1621         if (!target_was_examined(target))
1622         {
1623                 LOG_ERROR("Target not examined yet");
1624                 return ERROR_FAIL;
1625         }
1626
1627         int retval = target_read_memory(target, address, 2, 1, value_buf);
1628
1629         if (retval == ERROR_OK)
1630         {
1631                 *value = target_buffer_get_u16(target, value_buf);
1632                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1633                                   address,
1634                                   *value);
1635         }
1636         else
1637         {
1638                 *value = 0x0;
1639                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1640                                   address);
1641         }
1642
1643         return retval;
1644 }
1645
1646 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1647 {
1648         int retval = target_read_memory(target, address, 1, 1, value);
1649         if (!target_was_examined(target))
1650         {
1651                 LOG_ERROR("Target not examined yet");
1652                 return ERROR_FAIL;
1653         }
1654
1655         if (retval == ERROR_OK)
1656         {
1657                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1658                                   address,
1659                                   *value);
1660         }
1661         else
1662         {
1663                 *value = 0x0;
1664                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1665                                   address);
1666         }
1667
1668         return retval;
1669 }
1670
1671 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1672 {
1673         int retval;
1674         uint8_t value_buf[4];
1675         if (!target_was_examined(target))
1676         {
1677                 LOG_ERROR("Target not examined yet");
1678                 return ERROR_FAIL;
1679         }
1680
1681         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1682                           address,
1683                           value);
1684
1685         target_buffer_set_u32(target, value_buf, value);
1686         if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1687         {
1688                 LOG_DEBUG("failed: %i", retval);
1689         }
1690
1691         return retval;
1692 }
1693
1694 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1695 {
1696         int retval;
1697         uint8_t value_buf[2];
1698         if (!target_was_examined(target))
1699         {
1700                 LOG_ERROR("Target not examined yet");
1701                 return ERROR_FAIL;
1702         }
1703
1704         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1705                           address,
1706                           value);
1707
1708         target_buffer_set_u16(target, value_buf, value);
1709         if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1710         {
1711                 LOG_DEBUG("failed: %i", retval);
1712         }
1713
1714         return retval;
1715 }
1716
1717 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1718 {
1719         int retval;
1720         if (!target_was_examined(target))
1721         {
1722                 LOG_ERROR("Target not examined yet");
1723                 return ERROR_FAIL;
1724         }
1725
1726         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1727                           address, value);
1728
1729         if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1730         {
1731                 LOG_DEBUG("failed: %i", retval);
1732         }
1733
1734         return retval;
1735 }
1736
1737 COMMAND_HANDLER(handle_targets_command)
1738 {
1739         struct target *target = all_targets;
1740
1741         if (CMD_ARGC == 1)
1742         {
1743                 target = get_target(CMD_ARGV[0]);
1744                 if (target == NULL) {
1745                         command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1746                         goto DumpTargets;
1747                 }
1748                 if (!target->tap->enabled) {
1749                         command_print(CMD_CTX,"Target: TAP %s is disabled, "
1750                                         "can't be the current target\n",
1751                                         target->tap->dotted_name);
1752                         return ERROR_FAIL;
1753                 }
1754
1755                 CMD_CTX->current_target = target->target_number;
1756                 return ERROR_OK;
1757         }
1758 DumpTargets:
1759
1760         target = all_targets;
1761         command_print(CMD_CTX, "    TargetName         Type       Endian TapName            State       ");
1762         command_print(CMD_CTX, "--  ------------------ ---------- ------ ------------------ ------------");
1763         while (target)
1764         {
1765                 const char *state;
1766                 char marker = ' ';
1767
1768                 if (target->tap->enabled)
1769                         state = target_state_name( target );
1770                 else
1771                         state = "tap-disabled";
1772
1773                 if (CMD_CTX->current_target == target->target_number)
1774                         marker = '*';
1775
1776                 /* keep columns lined up to match the headers above */
1777                 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1778                                           target->target_number,
1779                                           marker,
1780                                           target_name(target),
1781                                           target_type_name(target),
1782                                           Jim_Nvp_value2name_simple(nvp_target_endian,
1783                                                                 target->endianness)->name,
1784                                           target->tap->dotted_name,
1785                                           state);
1786                 target = target->next;
1787         }
1788
1789         return ERROR_OK;
1790 }
1791
1792 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1793
1794 static int powerDropout;
1795 static int srstAsserted;
1796
1797 static int runPowerRestore;
1798 static int runPowerDropout;
1799 static int runSrstAsserted;
1800 static int runSrstDeasserted;
1801
1802 static int sense_handler(void)
1803 {
1804         static int prevSrstAsserted = 0;
1805         static int prevPowerdropout = 0;
1806
1807         int retval;
1808         if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1809                 return retval;
1810
1811         int powerRestored;
1812         powerRestored = prevPowerdropout && !powerDropout;
1813         if (powerRestored)
1814         {
1815                 runPowerRestore = 1;
1816         }
1817
1818         long long current = timeval_ms();
1819         static long long lastPower = 0;
1820         int waitMore = lastPower + 2000 > current;
1821         if (powerDropout && !waitMore)
1822         {
1823                 runPowerDropout = 1;
1824                 lastPower = current;
1825         }
1826
1827         if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1828                 return retval;
1829
1830         int srstDeasserted;
1831         srstDeasserted = prevSrstAsserted && !srstAsserted;
1832
1833         static long long lastSrst = 0;
1834         waitMore = lastSrst + 2000 > current;
1835         if (srstDeasserted && !waitMore)
1836         {
1837                 runSrstDeasserted = 1;
1838                 lastSrst = current;
1839         }
1840
1841         if (!prevSrstAsserted && srstAsserted)
1842         {
1843                 runSrstAsserted = 1;
1844         }
1845
1846         prevSrstAsserted = srstAsserted;
1847         prevPowerdropout = powerDropout;
1848
1849         if (srstDeasserted || powerRestored)
1850         {
1851                 /* Other than logging the event we can't do anything here.
1852                  * Issuing a reset is a particularly bad idea as we might
1853                  * be inside a reset already.
1854                  */
1855         }
1856
1857         return ERROR_OK;
1858 }
1859
1860 static int backoff_times = 0;
1861 static int backoff_count = 0;
1862
1863 /* process target state changes */
1864 static int handle_target(void *priv)
1865 {
1866         Jim_Interp *interp = (Jim_Interp *)priv;
1867         int retval = ERROR_OK;
1868
1869         if (!is_jtag_poll_safe())
1870         {
1871                 /* polling is disabled currently */
1872                 return ERROR_OK;
1873         }
1874
1875         /* we do not want to recurse here... */
1876         static int recursive = 0;
1877         if (! recursive)
1878         {
1879                 recursive = 1;
1880                 sense_handler();
1881                 /* danger! running these procedures can trigger srst assertions and power dropouts.
1882                  * We need to avoid an infinite loop/recursion here and we do that by
1883                  * clearing the flags after running these events.
1884                  */
1885                 int did_something = 0;
1886                 if (runSrstAsserted)
1887                 {
1888                         LOG_INFO("srst asserted detected, running srst_asserted proc.");
1889                         Jim_Eval(interp, "srst_asserted");
1890                         did_something = 1;
1891                 }
1892                 if (runSrstDeasserted)
1893                 {
1894                         Jim_Eval(interp, "srst_deasserted");
1895                         did_something = 1;
1896                 }
1897                 if (runPowerDropout)
1898                 {
1899                         LOG_INFO("Power dropout detected, running power_dropout proc.");
1900                         Jim_Eval(interp, "power_dropout");
1901                         did_something = 1;
1902                 }
1903                 if (runPowerRestore)
1904                 {
1905                         Jim_Eval(interp, "power_restore");
1906                         did_something = 1;
1907                 }
1908
1909                 if (did_something)
1910                 {
1911                         /* clear detect flags */
1912                         sense_handler();
1913                 }
1914
1915                 /* clear action flags */
1916
1917                 runSrstAsserted = 0;
1918                 runSrstDeasserted = 0;
1919                 runPowerRestore = 0;
1920                 runPowerDropout = 0;
1921
1922                 recursive = 0;
1923         }
1924
1925         if (backoff_times > backoff_count)
1926         {
1927                 /* do not poll this time as we failed previously */
1928                 backoff_count++;
1929                 return ERROR_OK;
1930         }
1931         backoff_count = 0;
1932
1933         /* Poll targets for state changes unless that's globally disabled.
1934          * Skip targets that are currently disabled.
1935          */
1936         for (struct target *target = all_targets;
1937                         is_jtag_poll_safe() && target;
1938                         target = target->next)
1939         {
1940                 if (!target->tap->enabled)
1941                         continue;
1942
1943                 /* only poll target if we've got power and srst isn't asserted */
1944                 if (!powerDropout && !srstAsserted)
1945                 {
1946                         /* polling may fail silently until the target has been examined */
1947                         if ((retval = target_poll(target)) != ERROR_OK)
1948                         {
1949                                 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1950                                 if (backoff_times * polling_interval < 5000)
1951                                 {
1952                                         backoff_times *= 2;
1953                                         backoff_times++;
1954                                 }
1955                                 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1956
1957                                 /* Tell GDB to halt the debugger. This allows the user to
1958                                  * run monitor commands to handle the situation.
1959                                  */
1960                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1961                                 return retval;
1962                         }
1963                         /* Since we succeeded, we reset backoff count */
1964                         if (backoff_times > 0)
1965                         {
1966                                 LOG_USER("Polling succeeded again");
1967                         }
1968                         backoff_times = 0;
1969                 }
1970         }
1971
1972         return retval;
1973 }
1974
1975 COMMAND_HANDLER(handle_reg_command)
1976 {
1977         struct target *target;
1978         struct reg *reg = NULL;
1979         unsigned count = 0;
1980         char *value;
1981
1982         LOG_DEBUG("-");
1983
1984         target = get_current_target(CMD_CTX);
1985
1986         /* list all available registers for the current target */
1987         if (CMD_ARGC == 0)
1988         {
1989                 struct reg_cache *cache = target->reg_cache;
1990
1991                 count = 0;
1992                 while (cache)
1993                 {
1994                         unsigned i;
1995
1996                         command_print(CMD_CTX, "===== %s", cache->name);
1997
1998                         for (i = 0, reg = cache->reg_list;
1999                                         i < cache->num_regs;
2000                                         i++, reg++, count++)
2001                         {
2002                                 /* only print cached values if they are valid */
2003                                 if (reg->valid) {
2004                                         value = buf_to_str(reg->value,
2005                                                         reg->size, 16);
2006                                         command_print(CMD_CTX,
2007                                                         "(%i) %s (/%" PRIu32 "): 0x%s%s",
2008                                                         count, reg->name,
2009                                                         reg->size, value,
2010                                                         reg->dirty
2011                                                                 ? " (dirty)"
2012                                                                 : "");
2013                                         free(value);
2014                                 } else {
2015                                         command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
2016                                                           count, reg->name,
2017                                                           reg->size) ;
2018                                 }
2019                         }
2020                         cache = cache->next;
2021                 }
2022
2023                 return ERROR_OK;
2024         }
2025
2026         /* access a single register by its ordinal number */
2027         if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
2028         {
2029                 unsigned num;
2030                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
2031
2032                 struct reg_cache *cache = target->reg_cache;
2033                 count = 0;
2034                 while (cache)
2035                 {
2036                         unsigned i;
2037                         for (i = 0; i < cache->num_regs; i++)
2038                         {
2039                                 if (count++ == num)
2040                                 {
2041                                         reg = &cache->reg_list[i];
2042                                         break;
2043                                 }
2044                         }
2045                         if (reg)
2046                                 break;
2047                         cache = cache->next;
2048                 }
2049
2050                 if (!reg)
2051                 {
2052                         command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2053                         return ERROR_OK;
2054                 }
2055         } else /* access a single register by its name */
2056         {
2057                 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2058
2059                 if (!reg)
2060                 {
2061                         command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2062                         return ERROR_OK;
2063                 }
2064         }
2065
2066         /* display a register */
2067         if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2068         {
2069                 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2070                         reg->valid = 0;
2071
2072                 if (reg->valid == 0)
2073                 {
2074                         reg->type->get(reg);
2075                 }
2076                 value = buf_to_str(reg->value, reg->size, 16);
2077                 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2078                 free(value);
2079                 return ERROR_OK;
2080         }
2081
2082         /* set register value */
2083         if (CMD_ARGC == 2)
2084         {
2085                 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2086                 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2087
2088                 reg->type->set(reg, buf);
2089
2090                 value = buf_to_str(reg->value, reg->size, 16);
2091                 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2092                 free(value);
2093
2094                 free(buf);
2095
2096                 return ERROR_OK;
2097         }
2098
2099         command_print(CMD_CTX, "usage: reg <#|name> [value]");
2100
2101         return ERROR_OK;
2102 }
2103
2104 COMMAND_HANDLER(handle_poll_command)
2105 {
2106         int retval = ERROR_OK;
2107         struct target *target = get_current_target(CMD_CTX);
2108
2109         if (CMD_ARGC == 0)
2110         {
2111                 command_print(CMD_CTX, "background polling: %s",
2112                                 jtag_poll_get_enabled() ? "on" : "off");
2113                 command_print(CMD_CTX, "TAP: %s (%s)",
2114                                 target->tap->dotted_name,
2115                                 target->tap->enabled ? "enabled" : "disabled");
2116                 if (!target->tap->enabled)
2117                         return ERROR_OK;
2118                 if ((retval = target_poll(target)) != ERROR_OK)
2119                         return retval;
2120                 if ((retval = target_arch_state(target)) != ERROR_OK)
2121                         return retval;
2122         }
2123         else if (CMD_ARGC == 1)
2124         {
2125                 bool enable;
2126                 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2127                 jtag_poll_set_enabled(enable);
2128         }
2129         else
2130         {
2131                 return ERROR_COMMAND_SYNTAX_ERROR;
2132         }
2133
2134         return retval;
2135 }
2136
2137 COMMAND_HANDLER(handle_wait_halt_command)
2138 {
2139         if (CMD_ARGC > 1)
2140                 return ERROR_COMMAND_SYNTAX_ERROR;
2141
2142         unsigned ms = 5000;
2143         if (1 == CMD_ARGC)
2144         {
2145                 int retval = parse_uint(CMD_ARGV[0], &ms);
2146                 if (ERROR_OK != retval)
2147                 {
2148                         command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2149                         return ERROR_COMMAND_SYNTAX_ERROR;
2150                 }
2151                 // convert seconds (given) to milliseconds (needed)
2152                 ms *= 1000;
2153         }
2154
2155         struct target *target = get_current_target(CMD_CTX);
2156         return target_wait_state(target, TARGET_HALTED, ms);
2157 }
2158
2159 /* wait for target state to change. The trick here is to have a low
2160  * latency for short waits and not to suck up all the CPU time
2161  * on longer waits.
2162  *
2163  * After 500ms, keep_alive() is invoked
2164  */
2165 int target_wait_state(struct target *target, enum target_state state, int ms)
2166 {
2167         int retval;
2168         long long then = 0, cur;
2169         int once = 1;
2170
2171         for (;;)
2172         {
2173                 if ((retval = target_poll(target)) != ERROR_OK)
2174                         return retval;
2175                 if (target->state == state)
2176                 {
2177                         break;
2178                 }
2179                 cur = timeval_ms();
2180                 if (once)
2181                 {
2182                         once = 0;
2183                         then = timeval_ms();
2184                         LOG_DEBUG("waiting for target %s...",
2185                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2186                 }
2187
2188                 if (cur-then > 500)
2189                 {
2190                         keep_alive();
2191                 }
2192
2193                 if ((cur-then) > ms)
2194                 {
2195                         LOG_ERROR("timed out while waiting for target %s",
2196                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2197                         return ERROR_FAIL;
2198                 }
2199         }
2200
2201         return ERROR_OK;
2202 }
2203
2204 COMMAND_HANDLER(handle_halt_command)
2205 {
2206         LOG_DEBUG("-");
2207
2208         struct target *target = get_current_target(CMD_CTX);
2209         int retval = target_halt(target);
2210         if (ERROR_OK != retval)
2211                 return retval;
2212
2213         if (CMD_ARGC == 1)
2214         {
2215                 unsigned wait_local;
2216                 retval = parse_uint(CMD_ARGV[0], &wait_local);
2217                 if (ERROR_OK != retval)
2218                         return ERROR_COMMAND_SYNTAX_ERROR;
2219                 if (!wait_local)
2220                         return ERROR_OK;
2221         }
2222
2223         return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2224 }
2225
2226 COMMAND_HANDLER(handle_soft_reset_halt_command)
2227 {
2228         struct target *target = get_current_target(CMD_CTX);
2229
2230         LOG_USER("requesting target halt and executing a soft reset");
2231
2232         target->type->soft_reset_halt(target);
2233
2234         return ERROR_OK;
2235 }
2236
2237 COMMAND_HANDLER(handle_reset_command)
2238 {
2239         if (CMD_ARGC > 1)
2240                 return ERROR_COMMAND_SYNTAX_ERROR;
2241
2242         enum target_reset_mode reset_mode = RESET_RUN;
2243         if (CMD_ARGC == 1)
2244         {
2245                 const Jim_Nvp *n;
2246                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2247                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2248                         return ERROR_COMMAND_SYNTAX_ERROR;
2249                 }
2250                 reset_mode = n->value;
2251         }
2252
2253         /* reset *all* targets */
2254         return target_process_reset(CMD_CTX, reset_mode);
2255 }
2256
2257
2258 COMMAND_HANDLER(handle_resume_command)
2259 {
2260         int current = 1;
2261         if (CMD_ARGC > 1)
2262                 return ERROR_COMMAND_SYNTAX_ERROR;
2263
2264         struct target *target = get_current_target(CMD_CTX);
2265         target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2266
2267         /* with no CMD_ARGV, resume from current pc, addr = 0,
2268          * with one arguments, addr = CMD_ARGV[0],
2269          * handle breakpoints, not debugging */
2270         uint32_t addr = 0;
2271         if (CMD_ARGC == 1)
2272         {
2273                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2274                 current = 0;
2275         }
2276
2277         return target_resume(target, current, addr, 1, 0);
2278 }
2279
2280 COMMAND_HANDLER(handle_step_command)
2281 {
2282         if (CMD_ARGC > 1)
2283                 return ERROR_COMMAND_SYNTAX_ERROR;
2284
2285         LOG_DEBUG("-");
2286
2287         /* with no CMD_ARGV, step from current pc, addr = 0,
2288          * with one argument addr = CMD_ARGV[0],
2289          * handle breakpoints, debugging */
2290         uint32_t addr = 0;
2291         int current_pc = 1;
2292         if (CMD_ARGC == 1)
2293         {
2294                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2295                 current_pc = 0;
2296         }
2297
2298         struct target *target = get_current_target(CMD_CTX);
2299
2300         return target->type->step(target, current_pc, addr, 1);
2301 }
2302
2303 static void handle_md_output(struct command_context *cmd_ctx,
2304                 struct target *target, uint32_t address, unsigned size,
2305                 unsigned count, const uint8_t *buffer)
2306 {
2307         const unsigned line_bytecnt = 32;
2308         unsigned line_modulo = line_bytecnt / size;
2309
2310         char output[line_bytecnt * 4 + 1];
2311         unsigned output_len = 0;
2312
2313         const char *value_fmt;
2314         switch (size) {
2315         case 4: value_fmt = "%8.8x "; break;
2316         case 2: value_fmt = "%4.4x "; break;
2317         case 1: value_fmt = "%2.2x "; break;
2318         default:
2319                 /* "can't happen", caller checked */
2320                 LOG_ERROR("invalid memory read size: %u", size);
2321                 return;
2322         }
2323
2324         for (unsigned i = 0; i < count; i++)
2325         {
2326                 if (i % line_modulo == 0)
2327                 {
2328                         output_len += snprintf(output + output_len,
2329                                         sizeof(output) - output_len,
2330                                         "0x%8.8x: ",
2331                                         (unsigned)(address + (i*size)));
2332                 }
2333
2334                 uint32_t value = 0;
2335                 const uint8_t *value_ptr = buffer + i * size;
2336                 switch (size) {
2337                 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2338                 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2339                 case 1: value = *value_ptr;
2340                 }
2341                 output_len += snprintf(output + output_len,
2342                                 sizeof(output) - output_len,
2343                                 value_fmt, value);
2344
2345                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2346                 {
2347                         command_print(cmd_ctx, "%s", output);
2348                         output_len = 0;
2349                 }
2350         }
2351 }
2352
2353 COMMAND_HANDLER(handle_md_command)
2354 {
2355         if (CMD_ARGC < 1)
2356                 return ERROR_COMMAND_SYNTAX_ERROR;
2357
2358         unsigned size = 0;
2359         switch (CMD_NAME[2]) {
2360         case 'w': size = 4; break;
2361         case 'h': size = 2; break;
2362         case 'b': size = 1; break;
2363         default: return ERROR_COMMAND_SYNTAX_ERROR;
2364         }
2365
2366         bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2367         int (*fn)(struct target *target,
2368                         uint32_t address, uint32_t size_value, uint32_t count, uint8_t *buffer);
2369         if (physical)
2370         {
2371                 CMD_ARGC--;
2372                 CMD_ARGV++;
2373                 fn=target_read_phys_memory;
2374         } else
2375         {
2376                 fn=target_read_memory;
2377         }
2378         if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2379         {
2380                 return ERROR_COMMAND_SYNTAX_ERROR;
2381         }
2382
2383         uint32_t address;
2384         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2385
2386         unsigned count = 1;
2387         if (CMD_ARGC == 2)
2388                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2389
2390         uint8_t *buffer = calloc(count, size);
2391
2392         struct target *target = get_current_target(CMD_CTX);
2393         int retval = fn(target, address, size, count, buffer);
2394         if (ERROR_OK == retval)
2395                 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2396
2397         free(buffer);
2398
2399         return retval;
2400 }
2401
2402 typedef int (*target_write_fn)(struct target *target,
2403                 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer);
2404
2405 static int target_write_memory_fast(struct target *target,
2406                 uint32_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
2407 {
2408         return target_write_buffer(target, address, size * count, buffer);
2409 }
2410
2411 static int target_fill_mem(struct target *target,
2412                 uint32_t address,
2413                 target_write_fn fn,
2414                 unsigned data_size,
2415                 /* value */
2416                 uint32_t b,
2417                 /* count */
2418                 unsigned c)
2419 {
2420         /* We have to write in reasonably large chunks to be able
2421          * to fill large memory areas with any sane speed */
2422         const unsigned chunk_size = 16384;
2423         uint8_t *target_buf = malloc(chunk_size * data_size);
2424         if (target_buf == NULL)
2425         {
2426                 LOG_ERROR("Out of memory");
2427                 return ERROR_FAIL;
2428         }
2429
2430         for (unsigned i = 0; i < chunk_size; i ++)
2431         {
2432                 switch (data_size)
2433                 {
2434                 case 4:
2435                         target_buffer_set_u32(target, target_buf + i*data_size, b);
2436                         break;
2437                 case 2:
2438                         target_buffer_set_u16(target, target_buf + i*data_size, b);
2439                         break;
2440                 case 1:
2441                         target_buffer_set_u8(target, target_buf + i*data_size, b);
2442                         break;
2443                 default:
2444                         exit(-1);
2445                 }
2446         }
2447
2448         int retval = ERROR_OK;
2449
2450         for (unsigned x = 0; x < c; x += chunk_size)
2451         {
2452                 unsigned current;
2453                 current = c - x;
2454                 if (current > chunk_size)
2455                 {
2456                         current = chunk_size;
2457                 }
2458                 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2459                 if (retval != ERROR_OK)
2460                 {
2461                         break;
2462                 }
2463                 /* avoid GDB timeouts */
2464                 keep_alive();
2465         }
2466         free(target_buf);
2467
2468         return retval;
2469 }
2470
2471
2472 COMMAND_HANDLER(handle_mw_command)
2473 {
2474         if (CMD_ARGC < 2)
2475         {
2476                 return ERROR_COMMAND_SYNTAX_ERROR;
2477         }
2478         bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2479         target_write_fn fn;
2480         if (physical)
2481         {
2482                 CMD_ARGC--;
2483                 CMD_ARGV++;
2484                 fn=target_write_phys_memory;
2485         } else
2486         {
2487                 fn = target_write_memory_fast;
2488         }
2489         if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2490                 return ERROR_COMMAND_SYNTAX_ERROR;
2491
2492         uint32_t address;
2493         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2494
2495         uint32_t value;
2496         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2497
2498         unsigned count = 1;
2499         if (CMD_ARGC == 3)
2500                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2501
2502         struct target *target = get_current_target(CMD_CTX);
2503         unsigned wordsize;
2504         switch (CMD_NAME[2])
2505         {
2506                 case 'w':
2507                         wordsize = 4;
2508                         break;
2509                 case 'h':
2510                         wordsize = 2;
2511                         break;
2512                 case 'b':
2513                         wordsize = 1;
2514                         break;
2515                 default:
2516                         return ERROR_COMMAND_SYNTAX_ERROR;
2517         }
2518
2519         return target_fill_mem(target, address, fn, wordsize, value, count);
2520 }
2521
2522 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2523                 uint32_t *min_address, uint32_t *max_address)
2524 {
2525         if (CMD_ARGC < 1 || CMD_ARGC > 5)
2526                 return ERROR_COMMAND_SYNTAX_ERROR;
2527
2528         /* a base address isn't always necessary,
2529          * default to 0x0 (i.e. don't relocate) */
2530         if (CMD_ARGC >= 2)
2531         {
2532                 uint32_t addr;
2533                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2534                 image->base_address = addr;
2535                 image->base_address_set = 1;
2536         }
2537         else
2538                 image->base_address_set = 0;
2539
2540         image->start_address_set = 0;
2541
2542         if (CMD_ARGC >= 4)
2543         {
2544                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2545         }
2546         if (CMD_ARGC == 5)
2547         {
2548                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2549                 // use size (given) to find max (required)
2550                 *max_address += *min_address;
2551         }
2552
2553         if (*min_address > *max_address)
2554                 return ERROR_COMMAND_SYNTAX_ERROR;
2555
2556         return ERROR_OK;
2557 }
2558
2559 COMMAND_HANDLER(handle_load_image_command)
2560 {
2561         uint8_t *buffer;
2562         size_t buf_cnt;
2563         uint32_t image_size;
2564         uint32_t min_address = 0;
2565         uint32_t max_address = 0xffffffff;
2566         int i;
2567         struct image image;
2568
2569         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2570                         &image, &min_address, &max_address);
2571         if (ERROR_OK != retval)
2572                 return retval;
2573
2574         struct target *target = get_current_target(CMD_CTX);
2575
2576         struct duration bench;
2577         duration_start(&bench);
2578
2579         if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2580         {
2581                 return ERROR_OK;
2582         }
2583
2584         image_size = 0x0;
2585         retval = ERROR_OK;
2586         for (i = 0; i < image.num_sections; i++)
2587         {
2588                 buffer = malloc(image.sections[i].size);
2589                 if (buffer == NULL)
2590                 {
2591                         command_print(CMD_CTX,
2592                                                   "error allocating buffer for section (%d bytes)",
2593                                                   (int)(image.sections[i].size));
2594                         break;
2595                 }
2596
2597                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2598                 {
2599                         free(buffer);
2600                         break;
2601                 }
2602
2603                 uint32_t offset = 0;
2604                 uint32_t length = buf_cnt;
2605
2606                 /* DANGER!!! beware of unsigned comparision here!!! */
2607
2608                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2609                                 (image.sections[i].base_address < max_address))
2610                 {
2611                         if (image.sections[i].base_address < min_address)
2612                         {
2613                                 /* clip addresses below */
2614                                 offset += min_address-image.sections[i].base_address;
2615                                 length -= offset;
2616                         }
2617
2618                         if (image.sections[i].base_address + buf_cnt > max_address)
2619                         {
2620                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2621                         }
2622
2623                         if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2624                         {
2625                                 free(buffer);
2626                                 break;
2627                         }
2628                         image_size += length;
2629                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2630                                                   (unsigned int)length,
2631                                                   image.sections[i].base_address + offset);
2632                 }
2633
2634                 free(buffer);
2635         }
2636
2637         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2638         {
2639                 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2640                                 "in %fs (%0.3f KiB/s)", image_size,
2641                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2642         }
2643
2644         image_close(&image);
2645
2646         return retval;
2647
2648 }
2649
2650 COMMAND_HANDLER(handle_dump_image_command)
2651 {
2652         struct fileio fileio;
2653         uint8_t buffer[560];
2654         int retval, retvaltemp;
2655         uint32_t address, size;
2656         struct duration bench;
2657         struct target *target = get_current_target(CMD_CTX);
2658
2659         if (CMD_ARGC != 3)
2660                 return ERROR_COMMAND_SYNTAX_ERROR;
2661
2662         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2663         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2664
2665         retval = fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY);
2666         if (retval != ERROR_OK)
2667                 return retval;
2668
2669         duration_start(&bench);
2670
2671         retval = ERROR_OK;
2672         while (size > 0)
2673         {
2674                 size_t size_written;
2675                 uint32_t this_run_size = (size > 560) ? 560 : size;
2676                 retval = target_read_buffer(target, address, this_run_size, buffer);
2677                 if (retval != ERROR_OK)
2678                 {
2679                         break;
2680                 }
2681
2682                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2683                 if (retval != ERROR_OK)
2684                 {
2685                         break;
2686                 }
2687
2688                 size -= this_run_size;
2689                 address += this_run_size;
2690         }
2691
2692         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2693         {
2694                 int filesize;
2695                 retval = fileio_size(&fileio, &filesize);
2696                 if (retval != ERROR_OK)
2697                         return retval;
2698                 command_print(CMD_CTX,
2699                                 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)filesize,
2700                                 duration_elapsed(&bench), duration_kbps(&bench, filesize));
2701         }
2702
2703         if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2704                 return retvaltemp;
2705
2706         return retval;
2707 }
2708
2709 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2710 {
2711         uint8_t *buffer;
2712         size_t buf_cnt;
2713         uint32_t image_size;
2714         int i;
2715         int retval;
2716         uint32_t checksum = 0;
2717         uint32_t mem_checksum = 0;
2718
2719         struct image image;
2720
2721         struct target *target = get_current_target(CMD_CTX);
2722
2723         if (CMD_ARGC < 1)
2724         {
2725                 return ERROR_COMMAND_SYNTAX_ERROR;
2726         }
2727
2728         if (!target)
2729         {
2730                 LOG_ERROR("no target selected");
2731                 return ERROR_FAIL;
2732         }
2733
2734         struct duration bench;
2735         duration_start(&bench);
2736
2737         if (CMD_ARGC >= 2)
2738         {
2739                 uint32_t addr;
2740                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2741                 image.base_address = addr;
2742                 image.base_address_set = 1;
2743         }
2744         else
2745         {
2746                 image.base_address_set = 0;
2747                 image.base_address = 0x0;
2748         }
2749
2750         image.start_address_set = 0;
2751
2752         if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2753         {
2754                 return retval;
2755         }
2756
2757         image_size = 0x0;
2758         int diffs = 0;
2759         retval = ERROR_OK;
2760         for (i = 0; i < image.num_sections; i++)
2761         {
2762                 buffer = malloc(image.sections[i].size);
2763                 if (buffer == NULL)
2764                 {
2765                         command_print(CMD_CTX,
2766                                                   "error allocating buffer for section (%d bytes)",
2767                                                   (int)(image.sections[i].size));
2768                         break;
2769                 }
2770                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2771                 {
2772                         free(buffer);
2773                         break;
2774                 }
2775
2776                 if (verify)
2777                 {
2778                         /* calculate checksum of image */
2779                         retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2780                         if (retval != ERROR_OK)
2781                         {
2782                                 free(buffer);
2783                                 break;
2784                         }
2785
2786                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2787                         if (retval != ERROR_OK)
2788                         {
2789                                 free(buffer);
2790                                 break;
2791                         }
2792
2793                         if (checksum != mem_checksum)
2794                         {
2795                                 /* failed crc checksum, fall back to a binary compare */
2796                                 uint8_t *data;
2797
2798                                 if (diffs == 0)
2799                                 {
2800                                         LOG_ERROR("checksum mismatch - attempting binary compare");
2801                                 }
2802
2803                                 data = (uint8_t*)malloc(buf_cnt);
2804
2805                                 /* Can we use 32bit word accesses? */
2806                                 int size = 1;
2807                                 int count = buf_cnt;
2808                                 if ((count % 4) == 0)
2809                                 {
2810                                         size *= 4;
2811                                         count /= 4;
2812                                 }
2813                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2814                                 if (retval == ERROR_OK)
2815                                 {
2816                                         uint32_t t;
2817                                         for (t = 0; t < buf_cnt; t++)
2818                                         {
2819                                                 if (data[t] != buffer[t])
2820                                                 {
2821                                                         command_print(CMD_CTX,
2822                                                                                   "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2823                                                                                   diffs,
2824                                                                                   (unsigned)(t + image.sections[i].base_address),
2825                                                                                   data[t],
2826                                                                                   buffer[t]);
2827                                                         if (diffs++ >= 127)
2828                                                         {
2829                                                                 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2830                                                                 free(data);
2831                                                                 free(buffer);
2832                                                                 goto done;
2833                                                         }
2834                                                 }
2835                                                 keep_alive();
2836                                         }
2837                                 }
2838                                 free(data);
2839                         }
2840                 } else
2841                 {
2842                         command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2843                                                   image.sections[i].base_address,
2844                                                   buf_cnt);
2845                 }
2846
2847                 free(buffer);
2848                 image_size += buf_cnt;
2849         }
2850         if (diffs > 0)
2851         {
2852                 command_print(CMD_CTX, "No more differences found.");
2853         }
2854 done:
2855         if (diffs > 0)
2856         {
2857                 retval = ERROR_FAIL;
2858         }
2859         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2860         {
2861                 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2862                                 "in %fs (%0.3f KiB/s)", image_size,
2863                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2864         }
2865
2866         image_close(&image);
2867
2868         return retval;
2869 }
2870
2871 COMMAND_HANDLER(handle_verify_image_command)
2872 {
2873         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2874 }
2875
2876 COMMAND_HANDLER(handle_test_image_command)
2877 {
2878         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2879 }
2880
2881 static int handle_bp_command_list(struct command_context *cmd_ctx)
2882 {
2883         struct target *target = get_current_target(cmd_ctx);
2884         struct breakpoint *breakpoint = target->breakpoints;
2885         while (breakpoint)
2886         {
2887                 if (breakpoint->type == BKPT_SOFT)
2888                 {
2889                         char* buf = buf_to_str(breakpoint->orig_instr,
2890                                         breakpoint->length, 16);
2891                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2892                                         breakpoint->address,
2893                                         breakpoint->length,
2894                                         breakpoint->set, buf);
2895                         free(buf);
2896                 }
2897                 else
2898                 {
2899                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2900                                                   breakpoint->address,
2901                                                   breakpoint->length, breakpoint->set);
2902                 }
2903
2904                 breakpoint = breakpoint->next;
2905         }
2906         return ERROR_OK;
2907 }
2908
2909 static int handle_bp_command_set(struct command_context *cmd_ctx,
2910                 uint32_t addr, uint32_t length, int hw)
2911 {
2912         struct target *target = get_current_target(cmd_ctx);
2913         int retval = breakpoint_add(target, addr, length, hw);
2914         if (ERROR_OK == retval)
2915                 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2916         else
2917                 LOG_ERROR("Failure setting breakpoint");
2918         return retval;
2919 }
2920
2921 COMMAND_HANDLER(handle_bp_command)
2922 {
2923         if (CMD_ARGC == 0)
2924                 return handle_bp_command_list(CMD_CTX);
2925
2926         if (CMD_ARGC < 2 || CMD_ARGC > 3)
2927         {
2928                 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2929                 return ERROR_COMMAND_SYNTAX_ERROR;
2930         }
2931
2932         uint32_t addr;
2933         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2934         uint32_t length;
2935         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2936
2937         int hw = BKPT_SOFT;
2938         if (CMD_ARGC == 3)
2939         {
2940                 if (strcmp(CMD_ARGV[2], "hw") == 0)
2941                         hw = BKPT_HARD;
2942                 else
2943                         return ERROR_COMMAND_SYNTAX_ERROR;
2944         }
2945
2946         return handle_bp_command_set(CMD_CTX, addr, length, hw);
2947 }
2948
2949 COMMAND_HANDLER(handle_rbp_command)
2950 {
2951         if (CMD_ARGC != 1)
2952                 return ERROR_COMMAND_SYNTAX_ERROR;
2953
2954         uint32_t addr;
2955         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2956
2957         struct target *target = get_current_target(CMD_CTX);
2958         breakpoint_remove(target, addr);
2959
2960         return ERROR_OK;
2961 }
2962
2963 COMMAND_HANDLER(handle_wp_command)
2964 {
2965         struct target *target = get_current_target(CMD_CTX);
2966
2967         if (CMD_ARGC == 0)
2968         {
2969                 struct watchpoint *watchpoint = target->watchpoints;
2970
2971                 while (watchpoint)
2972                 {
2973                         command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2974                                         ", len: 0x%8.8" PRIx32
2975                                         ", r/w/a: %i, value: 0x%8.8" PRIx32
2976                                         ", mask: 0x%8.8" PRIx32,
2977                                         watchpoint->address,
2978                                         watchpoint->length,
2979                                         (int)watchpoint->rw,
2980                                         watchpoint->value,
2981                                         watchpoint->mask);
2982                         watchpoint = watchpoint->next;
2983                 }
2984                 return ERROR_OK;
2985         }
2986
2987         enum watchpoint_rw type = WPT_ACCESS;
2988         uint32_t addr = 0;
2989         uint32_t length = 0;
2990         uint32_t data_value = 0x0;
2991         uint32_t data_mask = 0xffffffff;
2992
2993         switch (CMD_ARGC)
2994         {
2995         case 5:
2996                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2997                 // fall through
2998         case 4:
2999                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3000                 // fall through
3001         case 3:
3002                 switch (CMD_ARGV[2][0])
3003                 {
3004                 case 'r':
3005                         type = WPT_READ;
3006                         break;
3007                 case 'w':
3008                         type = WPT_WRITE;
3009                         break;
3010                 case 'a':
3011                         type = WPT_ACCESS;
3012                         break;
3013                 default:
3014                         LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3015                         return ERROR_COMMAND_SYNTAX_ERROR;
3016                 }
3017                 // fall through
3018         case 2:
3019                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3020                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3021                 break;
3022
3023         default:
3024                 command_print(CMD_CTX, "usage: wp [address length "
3025                                 "[(r|w|a) [value [mask]]]]");
3026                 return ERROR_COMMAND_SYNTAX_ERROR;
3027         }
3028
3029         int retval = watchpoint_add(target, addr, length, type,
3030                         data_value, data_mask);
3031         if (ERROR_OK != retval)
3032                 LOG_ERROR("Failure setting watchpoints");
3033
3034         return retval;
3035 }
3036
3037 COMMAND_HANDLER(handle_rwp_command)
3038 {
3039         if (CMD_ARGC != 1)
3040                 return ERROR_COMMAND_SYNTAX_ERROR;
3041
3042         uint32_t addr;
3043         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3044
3045         struct target *target = get_current_target(CMD_CTX);
3046         watchpoint_remove(target, addr);
3047
3048         return ERROR_OK;
3049 }
3050
3051
3052 /**
3053  * Translate a virtual address to a physical address.
3054  *
3055  * The low-level target implementation must have logged a detailed error
3056  * which is forwarded to telnet/GDB session.
3057  */
3058 COMMAND_HANDLER(handle_virt2phys_command)
3059 {
3060         if (CMD_ARGC != 1)
3061                 return ERROR_COMMAND_SYNTAX_ERROR;
3062
3063         uint32_t va;
3064         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3065         uint32_t pa;
3066
3067         struct target *target = get_current_target(CMD_CTX);
3068         int retval = target->type->virt2phys(target, va, &pa);
3069         if (retval == ERROR_OK)
3070                 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3071
3072         return retval;
3073 }
3074
3075 static void writeData(FILE *f, const void *data, size_t len)
3076 {
3077         size_t written = fwrite(data, 1, len, f);
3078         if (written != len)
3079                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3080 }
3081
3082 static void writeLong(FILE *f, int l)
3083 {
3084         int i;
3085         for (i = 0; i < 4; i++)
3086         {
3087                 char c = (l >> (i*8))&0xff;
3088                 writeData(f, &c, 1);
3089         }
3090
3091 }
3092
3093 static void writeString(FILE *f, char *s)
3094 {
3095         writeData(f, s, strlen(s));
3096 }
3097
3098 /* Dump a gmon.out histogram file. */
3099 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3100 {
3101         uint32_t i;
3102         FILE *f = fopen(filename, "w");
3103         if (f == NULL)
3104                 return;
3105         writeString(f, "gmon");
3106         writeLong(f, 0x00000001); /* Version */
3107         writeLong(f, 0); /* padding */
3108         writeLong(f, 0); /* padding */
3109         writeLong(f, 0); /* padding */
3110
3111         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
3112         writeData(f, &zero, 1);
3113
3114         /* figure out bucket size */
3115         uint32_t min = samples[0];
3116         uint32_t max = samples[0];
3117         for (i = 0; i < sampleNum; i++)
3118         {
3119                 if (min > samples[i])
3120                 {
3121                         min = samples[i];
3122                 }
3123                 if (max < samples[i])
3124                 {
3125                         max = samples[i];
3126                 }
3127         }
3128
3129         int addressSpace = (max-min + 1);
3130
3131         static const uint32_t maxBuckets = 16 * 1024; /* maximum buckets. */
3132         uint32_t length = addressSpace;
3133         if (length > maxBuckets)
3134         {
3135                 length = maxBuckets;
3136         }
3137         int *buckets = malloc(sizeof(int)*length);
3138         if (buckets == NULL)
3139         {
3140                 fclose(f);
3141                 return;
3142         }
3143         memset(buckets, 0, sizeof(int)*length);
3144         for (i = 0; i < sampleNum;i++)
3145         {
3146                 uint32_t address = samples[i];
3147                 long long a = address-min;
3148                 long long b = length-1;
3149                 long long c = addressSpace-1;
3150                 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3151                 buckets[index_t]++;
3152         }
3153
3154         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3155         writeLong(f, min);                      /* low_pc */
3156         writeLong(f, max);                      /* high_pc */
3157         writeLong(f, length);           /* # of samples */
3158         writeLong(f, 100);                      /* KLUDGE! We lie, ca. 100Hz best case. */
3159         writeString(f, "seconds");
3160         for (i = 0; i < (15-strlen("seconds")); i++)
3161                 writeData(f, &zero, 1);
3162         writeString(f, "s");
3163
3164         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3165
3166         char *data = malloc(2*length);
3167         if (data != NULL)
3168         {
3169                 for (i = 0; i < length;i++)
3170                 {
3171                         int val;
3172                         val = buckets[i];
3173                         if (val > 65535)
3174                         {
3175                                 val = 65535;
3176                         }
3177                         data[i*2]=val&0xff;
3178                         data[i*2 + 1]=(val >> 8)&0xff;
3179                 }
3180                 free(buckets);
3181                 writeData(f, data, length * 2);
3182                 free(data);
3183         } else
3184         {
3185                 free(buckets);
3186         }
3187
3188         fclose(f);
3189 }
3190
3191 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3192  * which will be used as a random sampling of PC */
3193 COMMAND_HANDLER(handle_profile_command)
3194 {
3195         struct target *target = get_current_target(CMD_CTX);
3196         struct timeval timeout, now;
3197
3198         gettimeofday(&timeout, NULL);
3199         if (CMD_ARGC != 2)
3200         {
3201                 return ERROR_COMMAND_SYNTAX_ERROR;
3202         }
3203         unsigned offset;
3204         COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3205
3206         timeval_add_time(&timeout, offset, 0);
3207
3208         /**
3209          * @todo: Some cores let us sample the PC without the
3210          * annoying halt/resume step; for example, ARMv7 PCSR.
3211          * Provide a way to use that more efficient mechanism.
3212          */
3213
3214         command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3215
3216         static const int maxSample = 10000;
3217         uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3218         if (samples == NULL)
3219                 return ERROR_OK;
3220
3221         int numSamples = 0;
3222         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3223         struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3224
3225         for (;;)
3226         {
3227                 int retval;
3228                 target_poll(target);
3229                 if (target->state == TARGET_HALTED)
3230                 {
3231                         uint32_t t=*((uint32_t *)reg->value);
3232                         samples[numSamples++]=t;
3233                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3234                         target_poll(target);
3235                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3236                 } else if (target->state == TARGET_RUNNING)
3237                 {
3238                         /* We want to quickly sample the PC. */
3239                         if ((retval = target_halt(target)) != ERROR_OK)
3240                         {
3241                                 free(samples);
3242                                 return retval;
3243                         }
3244                 } else
3245                 {
3246                         command_print(CMD_CTX, "Target not halted or running");
3247                         retval = ERROR_OK;
3248                         break;
3249                 }
3250                 if (retval != ERROR_OK)
3251                 {
3252                         break;
3253                 }
3254
3255                 gettimeofday(&now, NULL);
3256                 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3257                 {
3258                         command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3259                         if ((retval = target_poll(target)) != ERROR_OK)
3260                         {
3261                                 free(samples);
3262                                 return retval;
3263                         }
3264                         if (target->state == TARGET_HALTED)
3265                         {
3266                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3267                         }
3268                         if ((retval = target_poll(target)) != ERROR_OK)
3269                         {
3270                                 free(samples);
3271                                 return retval;
3272                         }
3273                         writeGmon(samples, numSamples, CMD_ARGV[1]);
3274                         command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3275                         break;
3276                 }
3277         }
3278         free(samples);
3279
3280         return ERROR_OK;
3281 }
3282
3283 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3284 {
3285         char *namebuf;
3286         Jim_Obj *nameObjPtr, *valObjPtr;
3287         int result;
3288
3289         namebuf = alloc_printf("%s(%d)", varname, idx);
3290         if (!namebuf)
3291                 return JIM_ERR;
3292
3293         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3294         valObjPtr = Jim_NewIntObj(interp, val);
3295         if (!nameObjPtr || !valObjPtr)
3296         {
3297                 free(namebuf);
3298                 return JIM_ERR;
3299         }
3300
3301         Jim_IncrRefCount(nameObjPtr);
3302         Jim_IncrRefCount(valObjPtr);
3303         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3304         Jim_DecrRefCount(interp, nameObjPtr);
3305         Jim_DecrRefCount(interp, valObjPtr);
3306         free(namebuf);
3307         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3308         return result;
3309 }
3310
3311 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3312 {
3313         struct command_context *context;
3314         struct target *target;
3315
3316         context = current_command_context(interp);
3317         assert (context != NULL);
3318
3319         target = get_current_target(context);
3320         if (target == NULL)
3321         {
3322                 LOG_ERROR("mem2array: no current target");
3323                 return JIM_ERR;
3324         }
3325
3326         return  target_mem2array(interp, target, argc-1, argv + 1);
3327 }
3328
3329 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3330 {
3331         long l;
3332         uint32_t width;
3333         int len;
3334         uint32_t addr;
3335         uint32_t count;
3336         uint32_t v;
3337         const char *varname;
3338         int  n, e, retval;
3339         uint32_t i;
3340
3341         /* argv[1] = name of array to receive the data
3342          * argv[2] = desired width
3343          * argv[3] = memory address
3344          * argv[4] = count of times to read
3345          */
3346         if (argc != 4) {
3347                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3348                 return JIM_ERR;
3349         }
3350         varname = Jim_GetString(argv[0], &len);
3351         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3352
3353         e = Jim_GetLong(interp, argv[1], &l);
3354         width = l;
3355         if (e != JIM_OK) {
3356                 return e;
3357         }
3358
3359         e = Jim_GetLong(interp, argv[2], &l);
3360         addr = l;
3361         if (e != JIM_OK) {
3362                 return e;
3363         }
3364         e = Jim_GetLong(interp, argv[3], &l);
3365         len = l;
3366         if (e != JIM_OK) {
3367                 return e;
3368         }
3369         switch (width) {
3370                 case 8:
3371                         width = 1;
3372                         break;
3373                 case 16:
3374                         width = 2;
3375                         break;
3376                 case 32:
3377                         width = 4;
3378                         break;
3379                 default:
3380                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3381                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3382                         return JIM_ERR;
3383         }
3384         if (len == 0) {
3385                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3386                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3387                 return JIM_ERR;
3388         }
3389         if ((addr + (len * width)) < addr) {
3390                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3391                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3392                 return JIM_ERR;
3393         }
3394         /* absurd transfer size? */
3395         if (len > 65536) {
3396                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3397                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3398                 return JIM_ERR;
3399         }
3400
3401         if ((width == 1) ||
3402                 ((width == 2) && ((addr & 1) == 0)) ||
3403                 ((width == 4) && ((addr & 3) == 0))) {
3404                 /* all is well */
3405         } else {
3406                 char buf[100];
3407                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3408                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3409                                 addr,
3410                                 width);
3411                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3412                 return JIM_ERR;
3413         }
3414
3415         /* Transfer loop */
3416
3417         /* index counter */
3418         n = 0;
3419
3420         size_t buffersize = 4096;
3421         uint8_t *buffer = malloc(buffersize);
3422         if (buffer == NULL)
3423                 return JIM_ERR;
3424
3425         /* assume ok */
3426         e = JIM_OK;
3427         while (len) {
3428                 /* Slurp... in buffer size chunks */
3429
3430                 count = len; /* in objects.. */
3431                 if (count > (buffersize/width)) {
3432                         count = (buffersize/width);
3433                 }
3434
3435                 retval = target_read_memory(target, addr, width, count, buffer);
3436                 if (retval != ERROR_OK) {
3437                         /* BOO !*/
3438                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3439                                           (unsigned int)addr,
3440                                           (int)width,
3441                                           (int)count);
3442                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3443                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3444                         e = JIM_ERR;
3445                         len = 0;
3446                 } else {
3447                         v = 0; /* shut up gcc */
3448                         for (i = 0 ;i < count ;i++, n++) {
3449                                 switch (width) {
3450                                         case 4:
3451                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
3452                                                 break;
3453                                         case 2:
3454                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
3455                                                 break;
3456                                         case 1:
3457                                                 v = buffer[i] & 0x0ff;
3458                                                 break;
3459                                 }
3460                                 new_int_array_element(interp, varname, n, v);
3461                         }
3462                         len -= count;
3463                 }
3464         }
3465
3466         free(buffer);
3467
3468         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3469
3470         return JIM_OK;
3471 }
3472
3473 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3474 {
3475         char *namebuf;
3476         Jim_Obj *nameObjPtr, *valObjPtr;
3477         int result;
3478         long l;
3479
3480         namebuf = alloc_printf("%s(%d)", varname, idx);
3481         if (!namebuf)
3482                 return JIM_ERR;
3483
3484         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3485         if (!nameObjPtr)
3486         {
3487                 free(namebuf);
3488                 return JIM_ERR;
3489         }
3490
3491         Jim_IncrRefCount(nameObjPtr);
3492         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3493         Jim_DecrRefCount(interp, nameObjPtr);
3494         free(namebuf);
3495         if (valObjPtr == NULL)
3496                 return JIM_ERR;
3497
3498         result = Jim_GetLong(interp, valObjPtr, &l);
3499         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3500         *val = l;
3501         return result;
3502 }
3503
3504 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3505 {
3506         struct command_context *context;
3507         struct target *target;
3508
3509         context = current_command_context(interp);
3510         assert (context != NULL);
3511
3512         target = get_current_target(context);
3513         if (target == NULL) {
3514                 LOG_ERROR("array2mem: no current target");
3515                 return JIM_ERR;
3516         }
3517
3518         return target_array2mem(interp,target, argc-1, argv + 1);
3519 }
3520
3521 static int target_array2mem(Jim_Interp *interp, struct target *target,
3522                 int argc, Jim_Obj *const *argv)
3523 {
3524         long l;
3525         uint32_t width;
3526         int len;
3527         uint32_t addr;
3528         uint32_t count;
3529         uint32_t v;
3530         const char *varname;
3531         int  n, e, retval;
3532         uint32_t i;
3533
3534         /* argv[1] = name of array to get the data
3535          * argv[2] = desired width
3536          * argv[3] = memory address
3537          * argv[4] = count to write
3538          */
3539         if (argc != 4) {
3540                 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3541                 return JIM_ERR;
3542         }
3543         varname = Jim_GetString(argv[0], &len);
3544         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3545
3546         e = Jim_GetLong(interp, argv[1], &l);
3547         width = l;
3548         if (e != JIM_OK) {
3549                 return e;
3550         }
3551
3552         e = Jim_GetLong(interp, argv[2], &l);
3553         addr = l;
3554         if (e != JIM_OK) {
3555                 return e;
3556         }
3557         e = Jim_GetLong(interp, argv[3], &l);
3558         len = l;
3559         if (e != JIM_OK) {
3560                 return e;
3561         }
3562         switch (width) {
3563                 case 8:
3564                         width = 1;
3565                         break;
3566                 case 16:
3567                         width = 2;
3568                         break;
3569                 case 32:
3570                         width = 4;
3571                         break;
3572                 default:
3573                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3574                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3575                         return JIM_ERR;
3576         }
3577         if (len == 0) {
3578                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3579                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3580                 return JIM_ERR;
3581         }
3582         if ((addr + (len * width)) < addr) {
3583                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3584                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3585                 return JIM_ERR;
3586         }
3587         /* absurd transfer size? */
3588         if (len > 65536) {
3589                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3590                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3591                 return JIM_ERR;
3592         }
3593
3594         if ((width == 1) ||
3595                 ((width == 2) && ((addr & 1) == 0)) ||
3596                 ((width == 4) && ((addr & 3) == 0))) {
3597                 /* all is well */
3598         } else {
3599                 char buf[100];
3600                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3601                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3602                                 (unsigned int)addr,
3603                                 (int)width);
3604                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3605                 return JIM_ERR;
3606         }
3607
3608         /* Transfer loop */
3609
3610         /* index counter */
3611         n = 0;
3612         /* assume ok */
3613         e = JIM_OK;
3614
3615         size_t buffersize = 4096;
3616         uint8_t *buffer = malloc(buffersize);
3617         if (buffer == NULL)
3618                 return JIM_ERR;
3619
3620         while (len) {
3621                 /* Slurp... in buffer size chunks */
3622
3623                 count = len; /* in objects.. */
3624                 if (count > (buffersize/width)) {
3625                         count = (buffersize/width);
3626                 }
3627
3628                 v = 0; /* shut up gcc */
3629                 for (i = 0 ;i < count ;i++, n++) {
3630                         get_int_array_element(interp, varname, n, &v);
3631                         switch (width) {
3632                         case 4:
3633                                 target_buffer_set_u32(target, &buffer[i*width], v);
3634                                 break;
3635                         case 2:
3636                                 target_buffer_set_u16(target, &buffer[i*width], v);
3637                                 break;
3638                         case 1:
3639                                 buffer[i] = v & 0x0ff;
3640                                 break;
3641                         }
3642                 }
3643                 len -= count;
3644
3645                 retval = target_write_memory(target, addr, width, count, buffer);
3646                 if (retval != ERROR_OK) {
3647                         /* BOO !*/
3648                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3649                                           (unsigned int)addr,
3650                                           (int)width,
3651                                           (int)count);
3652                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3653                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3654                         e = JIM_ERR;
3655                         len = 0;
3656                 }
3657         }
3658
3659         free(buffer);
3660
3661         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3662
3663         return JIM_OK;
3664 }
3665
3666 /* FIX? should we propagate errors here rather than printing them
3667  * and continuing?
3668  */
3669 void target_handle_event(struct target *target, enum target_event e)
3670 {
3671         struct target_event_action *teap;
3672
3673         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3674                 if (teap->event == e) {
3675                         LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3676                                            target->target_number,
3677                                            target_name(target),
3678                                            target_type_name(target),
3679                                            e,
3680                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3681                                            Jim_GetString(teap->body, NULL));
3682                         if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3683                         {
3684                                 Jim_MakeErrorMessage(teap->interp);
3685                                 command_print(NULL,"%s\n", Jim_GetString(Jim_GetResult(teap->interp), NULL));
3686                         }
3687                 }
3688         }
3689 }
3690
3691 /**
3692  * Returns true only if the target has a handler for the specified event.
3693  */
3694 bool target_has_event_action(struct target *target, enum target_event event)
3695 {
3696         struct target_event_action *teap;
3697
3698         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3699                 if (teap->event == event)
3700                         return true;
3701         }
3702         return false;
3703 }
3704
3705 enum target_cfg_param {
3706         TCFG_TYPE,
3707         TCFG_EVENT,
3708         TCFG_WORK_AREA_VIRT,
3709         TCFG_WORK_AREA_PHYS,
3710         TCFG_WORK_AREA_SIZE,
3711         TCFG_WORK_AREA_BACKUP,
3712         TCFG_ENDIAN,
3713         TCFG_VARIANT,
3714         TCFG_COREID,
3715         TCFG_CHAIN_POSITION,
3716         TCFG_DBGBASE,
3717         TCFG_RTOS,
3718 };
3719
3720 static Jim_Nvp nvp_config_opts[] = {
3721         { .name = "-type",             .value = TCFG_TYPE },
3722         { .name = "-event",            .value = TCFG_EVENT },
3723         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
3724         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
3725         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
3726         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3727         { .name = "-endian" ,          .value = TCFG_ENDIAN },
3728         { .name = "-variant",          .value = TCFG_VARIANT },
3729         { .name = "-coreid",           .value = TCFG_COREID },
3730         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
3731         { .name = "-dbgbase",          .value = TCFG_DBGBASE },
3732         { .name = "-rtos",             .value = TCFG_RTOS },
3733         { .name = NULL, .value = -1 }
3734 };
3735
3736 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3737 {
3738         Jim_Nvp *n;
3739         Jim_Obj *o;
3740         jim_wide w;
3741         char *cp;
3742         int e;
3743
3744         /* parse config or cget options ... */
3745         while (goi->argc > 0) {
3746                 Jim_SetEmptyResult(goi->interp);
3747                 /* Jim_GetOpt_Debug(goi); */
3748
3749                 if (target->type->target_jim_configure) {
3750                         /* target defines a configure function */
3751                         /* target gets first dibs on parameters */
3752                         e = (*(target->type->target_jim_configure))(target, goi);
3753                         if (e == JIM_OK) {
3754                                 /* more? */
3755                                 continue;
3756                         }
3757                         if (e == JIM_ERR) {
3758                                 /* An error */
3759                                 return e;
3760                         }
3761                         /* otherwise we 'continue' below */
3762                 }
3763                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3764                 if (e != JIM_OK) {
3765                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3766                         return e;
3767                 }
3768                 switch (n->value) {
3769                 case TCFG_TYPE:
3770                         /* not setable */
3771                         if (goi->isconfigure) {
3772                                 Jim_SetResultFormatted(goi->interp,
3773                                                 "not settable: %s", n->name);
3774                                 return JIM_ERR;
3775                         } else {
3776                         no_params:
3777                                 if (goi->argc != 0) {
3778                                         Jim_WrongNumArgs(goi->interp,
3779                                                         goi->argc, goi->argv,
3780                                                         "NO PARAMS");
3781                                         return JIM_ERR;
3782                                 }
3783                         }
3784                         Jim_SetResultString(goi->interp,
3785                                         target_type_name(target), -1);
3786                         /* loop for more */
3787                         break;
3788                 case TCFG_EVENT:
3789                         if (goi->argc == 0) {
3790                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3791                                 return JIM_ERR;
3792                         }
3793
3794                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3795                         if (e != JIM_OK) {
3796                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3797                                 return e;
3798                         }
3799
3800                         if (goi->isconfigure) {
3801                                 if (goi->argc != 1) {
3802                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3803                                         return JIM_ERR;
3804                                 }
3805                         } else {
3806                                 if (goi->argc != 0) {
3807                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3808                                         return JIM_ERR;
3809                                 }
3810                         }
3811
3812                         {
3813                                 struct target_event_action *teap;
3814
3815                                 teap = target->event_action;
3816                                 /* replace existing? */
3817                                 while (teap) {
3818                                         if (teap->event == (enum target_event)n->value) {
3819                                                 break;
3820                                         }
3821                                         teap = teap->next;
3822                                 }
3823
3824                                 if (goi->isconfigure) {
3825                                         bool replace = true;
3826                                         if (teap == NULL) {
3827                                                 /* create new */
3828                                                 teap = calloc(1, sizeof(*teap));
3829                                                 replace = false;
3830                                         }
3831                                         teap->event = n->value;
3832                                         teap->interp = goi->interp;
3833                                         Jim_GetOpt_Obj(goi, &o);
3834                                         if (teap->body) {
3835                                                 Jim_DecrRefCount(teap->interp, teap->body);
3836                                         }
3837                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
3838                                         /*
3839                                          * FIXME:
3840                                          *     Tcl/TK - "tk events" have a nice feature.
3841                                          *     See the "BIND" command.
3842                                          *    We should support that here.
3843                                          *     You can specify %X and %Y in the event code.
3844                                          *     The idea is: %T - target name.
3845                                          *     The idea is: %N - target number
3846                                          *     The idea is: %E - event name.
3847                                          */
3848                                         Jim_IncrRefCount(teap->body);
3849
3850                                         if (!replace)
3851                                         {
3852                                                 /* add to head of event list */
3853                                                 teap->next = target->event_action;
3854                                                 target->event_action = teap;
3855                                         }
3856                                         Jim_SetEmptyResult(goi->interp);
3857                                 } else {
3858                                         /* get */
3859                                         if (teap == NULL) {
3860                                                 Jim_SetEmptyResult(goi->interp);
3861                                         } else {
3862                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3863                                         }
3864                                 }
3865                         }
3866                         /* loop for more */
3867                         break;
3868
3869                 case TCFG_WORK_AREA_VIRT:
3870                         if (goi->isconfigure) {
3871                                 target_free_all_working_areas(target);
3872                                 e = Jim_GetOpt_Wide(goi, &w);
3873                                 if (e != JIM_OK) {
3874                                         return e;
3875                                 }
3876                                 target->working_area_virt = w;
3877                                 target->working_area_virt_spec = true;
3878                         } else {
3879                                 if (goi->argc != 0) {
3880                                         goto no_params;
3881                                 }
3882                         }
3883                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3884                         /* loop for more */
3885                         break;
3886
3887                 case TCFG_WORK_AREA_PHYS:
3888                         if (goi->isconfigure) {
3889                                 target_free_all_working_areas(target);
3890                                 e = Jim_GetOpt_Wide(goi, &w);
3891                                 if (e != JIM_OK) {
3892                                         return e;
3893                                 }
3894                                 target->working_area_phys = w;
3895                                 target->working_area_phys_spec = true;
3896                         } else {
3897                                 if (goi->argc != 0) {
3898                                         goto no_params;
3899                                 }
3900                         }
3901                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3902                         /* loop for more */
3903                         break;
3904
3905                 case TCFG_WORK_AREA_SIZE:
3906                         if (goi->isconfigure) {
3907                                 target_free_all_working_areas(target);
3908                                 e = Jim_GetOpt_Wide(goi, &w);
3909                                 if (e != JIM_OK) {
3910                                         return e;
3911                                 }
3912                                 target->working_area_size = w;
3913                         } else {
3914                                 if (goi->argc != 0) {
3915                                         goto no_params;
3916                                 }
3917                         }
3918                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3919                         /* loop for more */
3920                         break;
3921
3922                 case TCFG_WORK_AREA_BACKUP:
3923                         if (goi->isconfigure) {
3924                                 target_free_all_working_areas(target);
3925                                 e = Jim_GetOpt_Wide(goi, &w);
3926                                 if (e != JIM_OK) {
3927                                         return e;
3928                                 }
3929                                 /* make this exactly 1 or 0 */
3930                                 target->backup_working_area = (!!w);
3931                         } else {
3932                                 if (goi->argc != 0) {
3933                                         goto no_params;
3934                                 }
3935                         }
3936                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3937                         /* loop for more e*/
3938                         break;
3939
3940
3941                 case TCFG_ENDIAN:
3942                         if (goi->isconfigure) {
3943                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3944                                 if (e != JIM_OK) {
3945                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3946                                         return e;
3947                                 }
3948                                 target->endianness = n->value;
3949                         } else {
3950                                 if (goi->argc != 0) {
3951                                         goto no_params;
3952                                 }
3953                         }
3954                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3955                         if (n->name == NULL) {
3956                                 target->endianness = TARGET_LITTLE_ENDIAN;
3957                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3958                         }
3959                         Jim_SetResultString(goi->interp, n->name, -1);
3960                         /* loop for more */
3961                         break;
3962
3963                 case TCFG_VARIANT:
3964                         if (goi->isconfigure) {
3965                                 if (goi->argc < 1) {
3966                                         Jim_SetResultFormatted(goi->interp,
3967                                                                                    "%s ?STRING?",
3968                                                                                    n->name);
3969                                         return JIM_ERR;
3970                                 }
3971                                 if (target->variant) {
3972                                         free((void *)(target->variant));
3973                                 }
3974                                 e = Jim_GetOpt_String(goi, &cp, NULL);
3975                                 target->variant = strdup(cp);
3976                         } else {
3977                                 if (goi->argc != 0) {
3978                                         goto no_params;
3979                                 }
3980                         }
3981                         Jim_SetResultString(goi->interp, target->variant,-1);
3982                         /* loop for more */
3983                         break;
3984
3985                 case TCFG_COREID:
3986                         if (goi->isconfigure) {
3987                                 e = Jim_GetOpt_Wide(goi, &w);
3988                                 if (e != JIM_OK) {
3989                                         return e;
3990                                 }
3991                                 target->coreid = (int32_t)w;
3992                         } else {
3993                                 if (goi->argc != 0) {
3994                                         goto no_params;
3995                                 }
3996                         }
3997                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3998                         /* loop for more */
3999                         break;
4000
4001                 case TCFG_CHAIN_POSITION:
4002                         if (goi->isconfigure) {
4003                                 Jim_Obj *o_t;
4004                                 struct jtag_tap *tap;
4005                                 target_free_all_working_areas(target);
4006                                 e = Jim_GetOpt_Obj(goi, &o_t);
4007                                 if (e != JIM_OK) {
4008                                         return e;
4009                                 }
4010                                 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4011                                 if (tap == NULL) {
4012                                         return JIM_ERR;
4013                                 }
4014                                 /* make this exactly 1 or 0 */
4015                                 target->tap = tap;
4016                         } else {
4017                                 if (goi->argc != 0) {
4018                                         goto no_params;
4019                                 }
4020                         }
4021                         Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4022                         /* loop for more e*/
4023                         break;
4024                 case TCFG_DBGBASE:
4025                         if (goi->isconfigure) {
4026                                 e = Jim_GetOpt_Wide(goi, &w);
4027                                 if (e != JIM_OK) {
4028                                         return e;
4029                                 }
4030                                 target->dbgbase = (uint32_t)w;
4031                                 target->dbgbase_set = true;
4032                         } else {
4033                                 if (goi->argc != 0) {
4034                                         goto no_params;
4035                                 }
4036                         }
4037                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4038                         /* loop for more */
4039                         break;
4040
4041                 case TCFG_RTOS:
4042                         /* RTOS */
4043                         {
4044                                 int result = rtos_create( goi, target );
4045                                 if ( result != JIM_OK )
4046                                 {
4047                                         return result;
4048                                 }
4049                         }
4050                         /* loop for more */
4051                         break;
4052                 }
4053         } /* while (goi->argc) */
4054
4055
4056                 /* done - we return */
4057         return JIM_OK;
4058 }
4059
4060 static int
4061 jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4062 {
4063         Jim_GetOptInfo goi;
4064
4065         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4066         goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4067         int need_args = 1 + goi.isconfigure;
4068         if (goi.argc < need_args)
4069         {
4070                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4071                         goi.isconfigure
4072                                 ? "missing: -option VALUE ..."
4073                                 : "missing: -option ...");
4074                 return JIM_ERR;
4075         }
4076         struct target *target = Jim_CmdPrivData(goi.interp);
4077         return target_configure(&goi, target);
4078 }
4079
4080 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4081 {
4082         const char *cmd_name = Jim_GetString(argv[0], NULL);
4083
4084         Jim_GetOptInfo goi;
4085         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4086
4087         if (goi.argc < 2 || goi.argc > 4)
4088         {
4089                 Jim_SetResultFormatted(goi.interp,
4090                                 "usage: %s [phys] <address> <data> [<count>]", cmd_name);
4091                 return JIM_ERR;
4092         }
4093
4094         target_write_fn fn;
4095         fn = target_write_memory_fast;
4096
4097         int e;
4098         if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4099         {
4100                 /* consume it */
4101                 struct Jim_Obj *obj;
4102                 e = Jim_GetOpt_Obj(&goi, &obj);
4103                 if (e != JIM_OK)
4104                         return e;
4105
4106                 fn = target_write_phys_memory;
4107         }
4108
4109         jim_wide a;
4110         e = Jim_GetOpt_Wide(&goi, &a);
4111         if (e != JIM_OK)
4112                 return e;
4113
4114         jim_wide b;
4115         e = Jim_GetOpt_Wide(&goi, &b);
4116         if (e != JIM_OK)
4117                 return e;
4118
4119         jim_wide c = 1;
4120         if (goi.argc == 1)
4121         {
4122                 e = Jim_GetOpt_Wide(&goi, &c);
4123                 if (e != JIM_OK)
4124                         return e;
4125         }
4126
4127         /* all args must be consumed */
4128         if (goi.argc != 0)
4129         {
4130                 return JIM_ERR;
4131         }
4132
4133         struct target *target = Jim_CmdPrivData(goi.interp);
4134         unsigned data_size;
4135         if (strcasecmp(cmd_name, "mww") == 0) {
4136                 data_size = 4;
4137         }
4138         else if (strcasecmp(cmd_name, "mwh") == 0) {
4139                 data_size = 2;
4140         }
4141         else if (strcasecmp(cmd_name, "mwb") == 0) {
4142                 data_size = 1;
4143         } else {
4144                 LOG_ERROR("command '%s' unknown: ", cmd_name);
4145                 return JIM_ERR;
4146         }
4147
4148         return (target_fill_mem(target, a, fn, data_size, b, c) == ERROR_OK) ? JIM_OK : JIM_ERR;
4149 }
4150
4151 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4152 {
4153         const char *cmd_name = Jim_GetString(argv[0], NULL);
4154
4155         Jim_GetOptInfo goi;
4156         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4157
4158         if ((goi.argc < 1) || (goi.argc > 3))
4159         {
4160                 Jim_SetResultFormatted(goi.interp,
4161                                 "usage: %s [phys] <address> [<count>]", cmd_name);
4162                 return JIM_ERR;
4163         }
4164
4165         int (*fn)(struct target *target,
4166                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
4167         fn=target_read_memory;
4168
4169         int e;
4170         if (strcmp(Jim_GetString(argv[1], NULL), "phys") == 0)
4171         {
4172                 /* consume it */
4173                 struct Jim_Obj *obj;
4174                 e = Jim_GetOpt_Obj(&goi, &obj);
4175                 if (e != JIM_OK)
4176                         return e;
4177
4178                 fn=target_read_phys_memory;
4179         }
4180
4181         jim_wide a;
4182         e = Jim_GetOpt_Wide(&goi, &a);
4183         if (e != JIM_OK) {
4184                 return JIM_ERR;
4185         }
4186         jim_wide c;
4187         if (goi.argc == 1) {
4188                 e = Jim_GetOpt_Wide(&goi, &c);
4189                 if (e != JIM_OK) {
4190                         return JIM_ERR;
4191                 }
4192         } else {
4193                 c = 1;
4194         }
4195
4196         /* all args must be consumed */
4197         if (goi.argc != 0)
4198         {
4199                 return JIM_ERR;
4200         }
4201
4202         jim_wide b = 1; /* shut up gcc */
4203         if (strcasecmp(cmd_name, "mdw") == 0)
4204                 b = 4;
4205         else if (strcasecmp(cmd_name, "mdh") == 0)
4206                 b = 2;
4207         else if (strcasecmp(cmd_name, "mdb") == 0)
4208                 b = 1;
4209         else {
4210                 LOG_ERROR("command '%s' unknown: ", cmd_name);
4211                 return JIM_ERR;
4212         }
4213
4214         /* convert count to "bytes" */
4215         c = c * b;
4216
4217         struct target *target = Jim_CmdPrivData(goi.interp);
4218         uint8_t  target_buf[32];
4219         jim_wide x, y, z;
4220         while (c > 0) {
4221                 y = c;
4222                 if (y > 16) {
4223                         y = 16;
4224                 }
4225                 e = fn(target, a, b, y / b, target_buf);
4226                 if (e != ERROR_OK) {
4227                         char tmp[10];
4228                         snprintf(tmp, sizeof(tmp), "%08lx", (long)a);
4229                         Jim_SetResultFormatted(interp, "error reading target @ 0x%s", tmp);
4230                         return JIM_ERR;
4231                 }
4232
4233                 command_print(NULL, "0x%08x ", (int)(a));
4234                 switch (b) {
4235                 case 4:
4236                         for (x = 0; x < 16 && x < y; x += 4)
4237                         {
4238                                 z = target_buffer_get_u32(target, &(target_buf[ x ]));
4239                                 command_print(NULL, "%08x ", (int)(z));
4240                         }
4241                         for (; (x < 16) ; x += 4) {
4242                                 command_print(NULL, "         ");
4243                         }
4244                         break;
4245                 case 2:
4246                         for (x = 0; x < 16 && x < y; x += 2)
4247                         {
4248                                 z = target_buffer_get_u16(target, &(target_buf[ x ]));
4249                                 command_print(NULL, "%04x ", (int)(z));
4250                         }
4251                         for (; (x < 16) ; x += 2) {
4252                                 command_print(NULL, "     ");
4253                         }
4254                         break;
4255                 case 1:
4256                 default:
4257                         for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4258                                 z = target_buffer_get_u8(target, &(target_buf[ x ]));
4259                                 command_print(NULL, "%02x ", (int)(z));
4260                         }
4261                         for (; (x < 16) ; x += 1) {
4262                                 command_print(NULL, "   ");
4263                         }
4264                         break;
4265                 }
4266                 /* ascii-ify the bytes */
4267                 for (x = 0 ; x < y ; x++) {
4268                         if ((target_buf[x] >= 0x20) &&
4269                                 (target_buf[x] <= 0x7e)) {
4270                                 /* good */
4271                         } else {
4272                                 /* smack it */
4273                                 target_buf[x] = '.';
4274                         }
4275                 }
4276                 /* space pad  */
4277                 while (x < 16) {
4278                         target_buf[x] = ' ';
4279                         x++;
4280                 }
4281                 /* terminate */
4282                 target_buf[16] = 0;
4283                 /* print - with a newline */
4284                 command_print(NULL, "%s\n", target_buf);
4285                 /* NEXT... */
4286                 c -= 16;
4287                 a += 16;
4288         }
4289         return JIM_OK;
4290 }
4291
4292 static int jim_target_mem2array(Jim_Interp *interp,
4293                 int argc, Jim_Obj *const *argv)
4294 {
4295         struct target *target = Jim_CmdPrivData(interp);
4296         return target_mem2array(interp, target, argc - 1, argv + 1);
4297 }
4298
4299 static int jim_target_array2mem(Jim_Interp *interp,
4300                 int argc, Jim_Obj *const *argv)
4301 {
4302         struct target *target = Jim_CmdPrivData(interp);
4303         return target_array2mem(interp, target, argc - 1, argv + 1);
4304 }
4305
4306 static int jim_target_tap_disabled(Jim_Interp *interp)
4307 {
4308         Jim_SetResultFormatted(interp, "[TAP is disabled]");
4309         return JIM_ERR;
4310 }
4311
4312 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4313 {
4314         if (argc != 1)
4315         {
4316                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4317                 return JIM_ERR;
4318         }
4319         struct target *target = Jim_CmdPrivData(interp);
4320         if (!target->tap->enabled)
4321                 return jim_target_tap_disabled(interp);
4322
4323         int e = target->type->examine(target);
4324         if (e != ERROR_OK)
4325         {
4326                 return JIM_ERR;
4327         }
4328         return JIM_OK;
4329 }
4330
4331 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4332 {
4333         if (argc != 1)
4334         {
4335                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4336                 return JIM_ERR;
4337         }
4338         struct target *target = Jim_CmdPrivData(interp);
4339
4340         if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
4341                 return JIM_ERR;
4342
4343         return JIM_OK;
4344 }
4345
4346 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4347 {
4348         if (argc != 1)
4349         {
4350                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4351                 return JIM_ERR;
4352         }
4353         struct target *target = Jim_CmdPrivData(interp);
4354         if (!target->tap->enabled)
4355                 return jim_target_tap_disabled(interp);
4356
4357         int e;
4358         if (!(target_was_examined(target))) {
4359                 e = ERROR_TARGET_NOT_EXAMINED;
4360         } else {
4361                 e = target->type->poll(target);
4362         }
4363         if (e != ERROR_OK)
4364         {
4365                 return JIM_ERR;
4366         }
4367         return JIM_OK;
4368 }
4369
4370 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4371 {
4372         Jim_GetOptInfo goi;
4373         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4374
4375         if (goi.argc != 2)
4376         {
4377                 Jim_WrongNumArgs(interp, 0, argv,
4378                                 "([tT]|[fF]|assert|deassert) BOOL");
4379                 return JIM_ERR;
4380         }
4381
4382         Jim_Nvp *n;
4383         int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4384         if (e != JIM_OK)
4385         {
4386                 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4387                 return e;
4388         }
4389         /* the halt or not param */
4390         jim_wide a;
4391         e = Jim_GetOpt_Wide(&goi, &a);
4392         if (e != JIM_OK)
4393                 return e;
4394
4395         struct target *target = Jim_CmdPrivData(goi.interp);
4396         if (!target->tap->enabled)
4397                 return jim_target_tap_disabled(interp);
4398         if (!(target_was_examined(target)))
4399         {
4400                 LOG_ERROR("Target not examined yet");
4401                 return ERROR_TARGET_NOT_EXAMINED;
4402         }
4403         if (!target->type->assert_reset || !target->type->deassert_reset)
4404         {
4405                 Jim_SetResultFormatted(interp,
4406                                 "No target-specific reset for %s",
4407                                 target_name(target));
4408                 return JIM_ERR;
4409         }
4410         /* determine if we should halt or not. */
4411         target->reset_halt = !!a;
4412         /* When this happens - all workareas are invalid. */
4413         target_free_all_working_areas_restore(target, 0);
4414
4415         /* do the assert */
4416         if (n->value == NVP_ASSERT) {
4417                 e = target->type->assert_reset(target);
4418         } else {
4419                 e = target->type->deassert_reset(target);
4420         }
4421         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4422 }
4423
4424 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4425 {
4426         if (argc != 1) {
4427                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4428                 return JIM_ERR;
4429         }
4430         struct target *target = Jim_CmdPrivData(interp);
4431         if (!target->tap->enabled)
4432                 return jim_target_tap_disabled(interp);
4433         int e = target->type->halt(target);
4434         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4435 }
4436
4437 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4438 {
4439         Jim_GetOptInfo goi;
4440         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4441
4442         /* params:  <name>  statename timeoutmsecs */
4443         if (goi.argc != 2)
4444         {
4445                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4446                 Jim_SetResultFormatted(goi.interp,
4447                                 "%s <state_name> <timeout_in_msec>", cmd_name);
4448                 return JIM_ERR;
4449         }
4450
4451         Jim_Nvp *n;
4452         int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4453         if (e != JIM_OK) {
4454                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4455                 return e;
4456         }
4457         jim_wide a;
4458         e = Jim_GetOpt_Wide(&goi, &a);
4459         if (e != JIM_OK) {
4460                 return e;
4461         }
4462         struct target *target = Jim_CmdPrivData(interp);
4463         if (!target->tap->enabled)
4464                 return jim_target_tap_disabled(interp);
4465
4466         e = target_wait_state(target, n->value, a);
4467         if (e != ERROR_OK)
4468         {
4469                 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
4470                 Jim_SetResultFormatted(goi.interp,
4471                                 "target: %s wait %s fails (%#s) %s",
4472                                 target_name(target), n->name,
4473                                 eObj, target_strerror_safe(e));
4474                 Jim_FreeNewObj(interp, eObj);
4475                 return JIM_ERR;
4476         }
4477         return JIM_OK;
4478 }
4479 /* List for human, Events defined for this target.
4480  * scripts/programs should use 'name cget -event NAME'
4481  */
4482 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4483 {
4484         struct command_context *cmd_ctx = current_command_context(interp);
4485         assert (cmd_ctx != NULL);
4486
4487         struct target *target = Jim_CmdPrivData(interp);
4488         struct target_event_action *teap = target->event_action;
4489         command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4490                                    target->target_number,
4491                                    target_name(target));
4492         command_print(cmd_ctx, "%-25s | Body", "Event");
4493         command_print(cmd_ctx, "------------------------- | "
4494                         "----------------------------------------");
4495         while (teap)
4496         {
4497                 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4498                 command_print(cmd_ctx, "%-25s | %s",
4499                                 opt->name, Jim_GetString(teap->body, NULL));
4500                 teap = teap->next;
4501         }
4502         command_print(cmd_ctx, "***END***");
4503         return JIM_OK;
4504 }
4505 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4506 {
4507         if (argc != 1)
4508         {
4509                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4510                 return JIM_ERR;
4511         }
4512         struct target *target = Jim_CmdPrivData(interp);
4513         Jim_SetResultString(interp, target_state_name(target), -1);
4514         return JIM_OK;
4515 }
4516 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4517 {
4518         Jim_GetOptInfo goi;
4519         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4520         if (goi.argc != 1)
4521         {
4522                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4523                 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
4524                 return JIM_ERR;
4525         }
4526         Jim_Nvp *n;
4527         int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4528         if (e != JIM_OK)
4529         {
4530                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4531                 return e;
4532         }
4533         struct target *target = Jim_CmdPrivData(interp);
4534         target_handle_event(target, n->value);
4535         return JIM_OK;
4536 }
4537
4538 static const struct command_registration target_instance_command_handlers[] = {
4539         {
4540                 .name = "configure",
4541                 .mode = COMMAND_CONFIG,
4542                 .jim_handler = jim_target_configure,
4543                 .help  = "configure a new target for use",
4544                 .usage = "[target_attribute ...]",
4545         },
4546         {
4547                 .name = "cget",
4548                 .mode = COMMAND_ANY,
4549                 .jim_handler = jim_target_configure,
4550                 .help  = "returns the specified target attribute",
4551                 .usage = "target_attribute",
4552         },
4553         {
4554                 .name = "mww",
4555                 .mode = COMMAND_EXEC,
4556                 .jim_handler = jim_target_mw,
4557                 .help = "Write 32-bit word(s) to target memory",
4558                 .usage = "address data [count]",
4559         },
4560         {
4561                 .name = "mwh",
4562                 .mode = COMMAND_EXEC,
4563                 .jim_handler = jim_target_mw,
4564                 .help = "Write 16-bit half-word(s) to target memory",
4565                 .usage = "address data [count]",
4566         },
4567         {
4568                 .name = "mwb",
4569                 .mode = COMMAND_EXEC,
4570                 .jim_handler = jim_target_mw,
4571                 .help = "Write byte(s) to target memory",
4572                 .usage = "address data [count]",
4573         },
4574         {
4575                 .name = "mdw",
4576                 .mode = COMMAND_EXEC,
4577                 .jim_handler = jim_target_md,
4578                 .help = "Display target memory as 32-bit words",
4579                 .usage = "address [count]",
4580         },
4581         {
4582                 .name = "mdh",
4583                 .mode = COMMAND_EXEC,
4584                 .jim_handler = jim_target_md,
4585                 .help = "Display target memory as 16-bit half-words",
4586                 .usage = "address [count]",
4587         },
4588         {
4589                 .name = "mdb",
4590                 .mode = COMMAND_EXEC,
4591                 .jim_handler = jim_target_md,
4592                 .help = "Display target memory as 8-bit bytes",
4593                 .usage = "address [count]",
4594         },
4595         {
4596                 .name = "array2mem",
4597                 .mode = COMMAND_EXEC,
4598                 .jim_handler = jim_target_array2mem,
4599                 .help = "Writes Tcl array of 8/16/32 bit numbers "
4600                         "to target memory",
4601                 .usage = "arrayname bitwidth address count",
4602         },
4603         {
4604                 .name = "mem2array",
4605                 .mode = COMMAND_EXEC,
4606                 .jim_handler = jim_target_mem2array,
4607                 .help = "Loads Tcl array of 8/16/32 bit numbers "
4608                         "from target memory",
4609                 .usage = "arrayname bitwidth address count",
4610         },
4611         {
4612                 .name = "eventlist",
4613                 .mode = COMMAND_EXEC,
4614                 .jim_handler = jim_target_event_list,
4615                 .help = "displays a table of events defined for this target",
4616         },
4617         {
4618                 .name = "curstate",
4619                 .mode = COMMAND_EXEC,
4620                 .jim_handler = jim_target_current_state,
4621                 .help = "displays the current state of this target",
4622         },
4623         {
4624                 .name = "arp_examine",
4625                 .mode = COMMAND_EXEC,
4626                 .jim_handler = jim_target_examine,
4627                 .help = "used internally for reset processing",
4628         },
4629         {
4630                 .name = "arp_halt_gdb",
4631                 .mode = COMMAND_EXEC,
4632                 .jim_handler = jim_target_halt_gdb,
4633                 .help = "used internally for reset processing to halt GDB",
4634         },
4635         {
4636                 .name = "arp_poll",
4637                 .mode = COMMAND_EXEC,
4638                 .jim_handler = jim_target_poll,
4639                 .help = "used internally for reset processing",
4640         },
4641         {
4642                 .name = "arp_reset",
4643                 .mode = COMMAND_EXEC,
4644                 .jim_handler = jim_target_reset,
4645                 .help = "used internally for reset processing",
4646         },
4647         {
4648                 .name = "arp_halt",
4649                 .mode = COMMAND_EXEC,
4650                 .jim_handler = jim_target_halt,
4651                 .help = "used internally for reset processing",
4652         },
4653         {
4654                 .name = "arp_waitstate",
4655                 .mode = COMMAND_EXEC,
4656                 .jim_handler = jim_target_wait_state,
4657                 .help = "used internally for reset processing",
4658         },
4659         {
4660                 .name = "invoke-event",
4661                 .mode = COMMAND_EXEC,
4662                 .jim_handler = jim_target_invoke_event,
4663                 .help = "invoke handler for specified event",
4664                 .usage = "event_name",
4665         },
4666         COMMAND_REGISTRATION_DONE
4667 };
4668
4669 static int target_create(Jim_GetOptInfo *goi)
4670 {
4671         Jim_Obj *new_cmd;
4672         Jim_Cmd *cmd;
4673         const char *cp;
4674         char *cp2;
4675         int e;
4676         int x;
4677         struct target *target;
4678         struct command_context *cmd_ctx;
4679
4680         cmd_ctx = current_command_context(goi->interp);
4681         assert (cmd_ctx != NULL);
4682
4683         if (goi->argc < 3) {
4684                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4685                 return JIM_ERR;
4686         }
4687
4688         /* COMMAND */
4689         Jim_GetOpt_Obj(goi, &new_cmd);
4690         /* does this command exist? */
4691         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4692         if (cmd) {
4693                 cp = Jim_GetString(new_cmd, NULL);
4694                 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
4695                 return JIM_ERR;
4696         }
4697
4698         /* TYPE */
4699         e = Jim_GetOpt_String(goi, &cp2, NULL);
4700         cp = cp2;
4701         /* now does target type exist */
4702         for (x = 0 ; target_types[x] ; x++) {
4703                 if (0 == strcmp(cp, target_types[x]->name)) {
4704                         /* found */
4705                         break;
4706                 }
4707         }
4708         if (target_types[x] == NULL) {
4709                 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
4710                 for (x = 0 ; target_types[x] ; x++) {
4711                         if (target_types[x + 1]) {
4712                                 Jim_AppendStrings(goi->interp,
4713                                                                    Jim_GetResult(goi->interp),
4714                                                                    target_types[x]->name,
4715                                                                    ", ", NULL);
4716                         } else {
4717                                 Jim_AppendStrings(goi->interp,
4718                                                                    Jim_GetResult(goi->interp),
4719                                                                    " or ",
4720                                                                    target_types[x]->name,NULL);
4721                         }
4722                 }
4723                 return JIM_ERR;
4724         }
4725
4726         /* Create it */
4727         target = calloc(1,sizeof(struct target));
4728         /* set target number */
4729         target->target_number = new_target_number();
4730
4731         /* allocate memory for each unique target type */
4732         target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4733
4734         memcpy(target->type, target_types[x], sizeof(struct target_type));
4735
4736         /* will be set by "-endian" */
4737         target->endianness = TARGET_ENDIAN_UNKNOWN;
4738
4739         /* default to first core, override with -coreid */
4740         target->coreid = 0;
4741
4742         target->working_area        = 0x0;
4743         target->working_area_size   = 0x0;
4744         target->working_areas       = NULL;
4745         target->backup_working_area = 0;
4746
4747         target->state               = TARGET_UNKNOWN;
4748         target->debug_reason        = DBG_REASON_UNDEFINED;
4749         target->reg_cache           = NULL;
4750         target->breakpoints         = NULL;
4751         target->watchpoints         = NULL;
4752         target->next                = NULL;
4753         target->arch_info           = NULL;
4754
4755         target->display             = 1;
4756
4757         target->halt_issued                     = false;
4758
4759         /* initialize trace information */
4760         target->trace_info = malloc(sizeof(struct trace));
4761         target->trace_info->num_trace_points         = 0;
4762         target->trace_info->trace_points_size        = 0;
4763         target->trace_info->trace_points             = NULL;
4764         target->trace_info->trace_history_size       = 0;
4765         target->trace_info->trace_history            = NULL;
4766         target->trace_info->trace_history_pos        = 0;
4767         target->trace_info->trace_history_overflowed = 0;
4768
4769         target->dbgmsg          = NULL;
4770         target->dbg_msg_enabled = 0;
4771
4772         target->endianness = TARGET_ENDIAN_UNKNOWN;
4773
4774         target->rtos = NULL;
4775         target->rtos_auto_detect = false;
4776
4777         /* Do the rest as "configure" options */
4778         goi->isconfigure = 1;
4779         e = target_configure(goi, target);
4780
4781         if (target->tap == NULL)
4782         {
4783                 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4784                 e = JIM_ERR;
4785         }
4786
4787         if (e != JIM_OK) {
4788                 free(target->type);
4789                 free(target);
4790                 return e;
4791         }
4792
4793         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4794                 /* default endian to little if not specified */
4795                 target->endianness = TARGET_LITTLE_ENDIAN;
4796         }
4797
4798         /* incase variant is not set */
4799         if (!target->variant)
4800                 target->variant = strdup("");
4801
4802         cp = Jim_GetString(new_cmd, NULL);
4803         target->cmd_name = strdup(cp);
4804
4805         /* create the target specific commands */
4806         if (target->type->commands) {
4807                 e = register_commands(cmd_ctx, NULL, target->type->commands);
4808                 if (ERROR_OK != e)
4809                         LOG_ERROR("unable to register '%s' commands", cp);
4810         }
4811         if (target->type->target_create) {
4812                 (*(target->type->target_create))(target, goi->interp);
4813         }
4814
4815         /* append to end of list */
4816         {
4817                 struct target **tpp;
4818                 tpp = &(all_targets);
4819                 while (*tpp) {
4820                         tpp = &((*tpp)->next);
4821                 }
4822                 *tpp = target;
4823         }
4824
4825         /* now - create the new target name command */
4826         const const struct command_registration target_subcommands[] = {
4827                 {
4828                         .chain = target_instance_command_handlers,
4829                 },
4830                 {
4831                         .chain = target->type->commands,
4832                 },
4833                 COMMAND_REGISTRATION_DONE
4834         };
4835         const const struct command_registration target_commands[] = {
4836                 {
4837                         .name = cp,
4838                         .mode = COMMAND_ANY,
4839                         .help = "target command group",
4840                         .chain = target_subcommands,
4841                 },
4842                 COMMAND_REGISTRATION_DONE
4843         };
4844         e = register_commands(cmd_ctx, NULL, target_commands);
4845         if (ERROR_OK != e)
4846                 return JIM_ERR;
4847
4848         struct command *c = command_find_in_context(cmd_ctx, cp);
4849         assert(c);
4850         command_set_handler_data(c, target);
4851
4852         return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4853 }
4854
4855 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4856 {
4857         if (argc != 1)
4858         {
4859                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4860                 return JIM_ERR;
4861         }
4862         struct command_context *cmd_ctx = current_command_context(interp);
4863         assert (cmd_ctx != NULL);
4864
4865         Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4866         return JIM_OK;
4867 }
4868
4869 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4870 {
4871         if (argc != 1)
4872         {
4873                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4874                 return JIM_ERR;
4875         }
4876         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4877         for (unsigned x = 0; NULL != target_types[x]; x++)
4878         {
4879                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4880                         Jim_NewStringObj(interp, target_types[x]->name, -1));
4881         }
4882         return JIM_OK;
4883 }
4884
4885 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4886 {
4887         if (argc != 1)
4888         {
4889                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4890                 return JIM_ERR;
4891         }
4892         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4893         struct target *target = all_targets;
4894         while (target)
4895         {
4896                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4897                         Jim_NewStringObj(interp, target_name(target), -1));
4898                 target = target->next;
4899         }
4900         return JIM_OK;
4901 }
4902
4903 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4904 {
4905         int i;
4906         const char *targetname;
4907         int retval,len;
4908         struct target *target;
4909         struct target_list *head, *curr, *new;
4910     curr = (struct target_list*) NULL;
4911         head = (struct target_list*) NULL;
4912         new = (struct target_list*) NULL;
4913
4914         retval = 0;
4915         LOG_DEBUG("%d",argc);
4916         /* argv[1] = target to associate in smp
4917          * argv[2] = target to assoicate in smp 
4918          * argv[3] ...
4919          */
4920
4921         for(i=1;i<argc;i++)
4922         {
4923
4924                 targetname = Jim_GetString(argv[i], &len);
4925                 target = get_target(targetname);
4926                 LOG_DEBUG("%s ",targetname);
4927                 if (target)
4928                 {
4929                         new=malloc(sizeof(struct target_list));
4930                         new->target = target;
4931                         new->next = (struct target_list*)NULL;
4932                         if (head == (struct target_list*)NULL)
4933                         {
4934                                 head = new;
4935                                 curr = head;
4936                         }
4937                         else
4938                         {
4939                                 curr->next = new;
4940                                 curr = new;
4941                         }
4942                 }
4943         }
4944     /*  now parse the list of cpu and put the target in smp mode*/
4945         curr=head;
4946
4947     while(curr!=(struct target_list *)NULL)
4948         {
4949     target=curr->target;
4950         target->smp = 1;
4951         target->head = head;
4952         curr=curr->next;
4953         }
4954         return retval; 
4955 }
4956
4957
4958 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4959 {
4960         Jim_GetOptInfo goi;
4961         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4962         if (goi.argc < 3)
4963         {
4964                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4965                         "<name> <target_type> [<target_options> ...]");
4966                 return JIM_ERR;
4967         }
4968         return target_create(&goi);
4969 }
4970
4971 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4972 {
4973         Jim_GetOptInfo goi;
4974         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4975
4976         /* It's OK to remove this mechanism sometime after August 2010 or so */
4977         LOG_WARNING("don't use numbers as target identifiers; use names");
4978         if (goi.argc != 1)
4979         {
4980                 Jim_SetResultFormatted(goi.interp, "usage: target number <number>");
4981                 return JIM_ERR;
4982         }
4983         jim_wide w;
4984         int e = Jim_GetOpt_Wide(&goi, &w);
4985         if (e != JIM_OK)
4986                 return JIM_ERR;
4987
4988         struct target *target;
4989         for (target = all_targets; NULL != target; target = target->next)
4990         {
4991                 if (target->target_number != w)
4992                         continue;
4993
4994                 Jim_SetResultString(goi.interp, target_name(target), -1);
4995                 return JIM_OK;
4996         }
4997         {
4998                 Jim_Obj *wObj = Jim_NewIntObj(goi.interp, w);
4999                 Jim_SetResultFormatted(goi.interp,
5000                         "Target: number %#s does not exist", wObj);
5001                 Jim_FreeNewObj(interp, wObj);
5002         }
5003         return JIM_ERR;
5004 }
5005
5006 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5007 {
5008         if (argc != 1)
5009         {
5010                 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
5011                 return JIM_ERR;
5012         }
5013         unsigned count = 0;
5014         struct target *target = all_targets;
5015         while (NULL != target)
5016         {
5017                 target = target->next;
5018                 count++;
5019         }
5020         Jim_SetResult(interp, Jim_NewIntObj(interp, count));
5021         return JIM_OK;
5022 }
5023
5024 static const struct command_registration target_subcommand_handlers[] = {
5025         {
5026                 .name = "init",
5027                 .mode = COMMAND_CONFIG,
5028                 .handler = handle_target_init_command,
5029                 .help = "initialize targets",
5030         },
5031         {
5032                 .name = "create",
5033                 /* REVISIT this should be COMMAND_CONFIG ... */
5034                 .mode = COMMAND_ANY,
5035                 .jim_handler = jim_target_create,
5036                 .usage = "name type '-chain-position' name [options ...]",
5037                 .help = "Creates and selects a new target",
5038         },
5039         {
5040                 .name = "current",
5041                 .mode = COMMAND_ANY,
5042                 .jim_handler = jim_target_current,
5043                 .help = "Returns the currently selected target",
5044         },
5045         {
5046                 .name = "types",
5047                 .mode = COMMAND_ANY,
5048                 .jim_handler = jim_target_types,
5049                 .help = "Returns the available target types as "
5050                                 "a list of strings",
5051         },
5052         {
5053                 .name = "names",
5054                 .mode = COMMAND_ANY,
5055                 .jim_handler = jim_target_names,
5056                 .help = "Returns the names of all targets as a list of strings",
5057         },
5058         {
5059                 .name = "number",
5060                 .mode = COMMAND_ANY,
5061                 .jim_handler = jim_target_number,
5062                 .usage = "number",
5063                 .help = "Returns the name of the numbered target "
5064                         "(DEPRECATED)",
5065         },
5066         {
5067                 .name = "count",
5068                 .mode = COMMAND_ANY,
5069                 .jim_handler = jim_target_count,
5070                 .help = "Returns the number of targets as an integer "
5071                         "(DEPRECATED)",
5072         },
5073         {
5074                 .name = "smp",
5075                 .mode = COMMAND_ANY,
5076                 .jim_handler = jim_target_smp,
5077                 .usage = "targetname1 targetname2 ...",
5078                 .help = "gather several target in a smp list"
5079         },
5080
5081         COMMAND_REGISTRATION_DONE
5082 };
5083
5084 struct FastLoad
5085 {
5086         uint32_t address;
5087         uint8_t *data;
5088         int length;
5089
5090 };
5091
5092 static int fastload_num;
5093 static struct FastLoad *fastload;
5094
5095 static void free_fastload(void)
5096 {
5097         if (fastload != NULL)
5098         {
5099                 int i;
5100                 for (i = 0; i < fastload_num; i++)
5101                 {
5102                         if (fastload[i].data)
5103                                 free(fastload[i].data);
5104                 }
5105                 free(fastload);
5106                 fastload = NULL;
5107         }
5108 }
5109
5110
5111
5112
5113 COMMAND_HANDLER(handle_fast_load_image_command)
5114 {
5115         uint8_t *buffer;
5116         size_t buf_cnt;
5117         uint32_t image_size;
5118         uint32_t min_address = 0;
5119         uint32_t max_address = 0xffffffff;
5120         int i;
5121
5122         struct image image;
5123
5124         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5125                         &image, &min_address, &max_address);
5126         if (ERROR_OK != retval)
5127                 return retval;
5128
5129         struct duration bench;
5130         duration_start(&bench);
5131
5132         retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5133         if (retval != ERROR_OK)
5134         {
5135                 return retval;
5136         }
5137
5138         image_size = 0x0;
5139         retval = ERROR_OK;
5140         fastload_num = image.num_sections;
5141         fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
5142         if (fastload == NULL)
5143         {
5144                 command_print(CMD_CTX, "out of memory");
5145                 image_close(&image);
5146                 return ERROR_FAIL;
5147         }
5148         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5149         for (i = 0; i < image.num_sections; i++)
5150         {
5151                 buffer = malloc(image.sections[i].size);
5152                 if (buffer == NULL)
5153                 {
5154                         command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5155                                                   (int)(image.sections[i].size));
5156                         retval = ERROR_FAIL;
5157                         break;
5158                 }
5159
5160                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
5161                 {
5162                         free(buffer);
5163                         break;
5164                 }
5165
5166                 uint32_t offset = 0;
5167                 uint32_t length = buf_cnt;
5168
5169
5170                 /* DANGER!!! beware of unsigned comparision here!!! */
5171
5172                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
5173                                 (image.sections[i].base_address < max_address))
5174                 {
5175                         if (image.sections[i].base_address < min_address)
5176                         {
5177                                 /* clip addresses below */
5178                                 offset += min_address-image.sections[i].base_address;
5179                                 length -= offset;
5180                         }
5181
5182                         if (image.sections[i].base_address + buf_cnt > max_address)
5183                         {
5184                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5185                         }
5186
5187                         fastload[i].address = image.sections[i].base_address + offset;
5188                         fastload[i].data = malloc(length);
5189                         if (fastload[i].data == NULL)
5190                         {
5191                                 free(buffer);
5192                                 command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
5193                                                           length);
5194                                 retval = ERROR_FAIL;
5195                                 break;
5196                         }
5197                         memcpy(fastload[i].data, buffer + offset, length);
5198                         fastload[i].length = length;
5199
5200                         image_size += length;
5201                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
5202                                                   (unsigned int)length,
5203                                                   ((unsigned int)(image.sections[i].base_address + offset)));
5204                 }
5205
5206                 free(buffer);
5207         }
5208
5209         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
5210         {
5211                 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
5212                                 "in %fs (%0.3f KiB/s)", image_size,
5213                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5214
5215                 command_print(CMD_CTX,
5216                                 "WARNING: image has not been loaded to target!"
5217                                 "You can issue a 'fast_load' to finish loading.");
5218         }
5219
5220         image_close(&image);
5221
5222         if (retval != ERROR_OK)
5223         {
5224                 free_fastload();
5225         }
5226
5227         return retval;
5228 }
5229
5230 COMMAND_HANDLER(handle_fast_load_command)
5231 {
5232         if (CMD_ARGC > 0)
5233                 return ERROR_COMMAND_SYNTAX_ERROR;
5234         if (fastload == NULL)
5235         {
5236                 LOG_ERROR("No image in memory");
5237                 return ERROR_FAIL;
5238         }
5239         int i;
5240         int ms = timeval_ms();
5241         int size = 0;
5242         int retval = ERROR_OK;
5243         for (i = 0; i < fastload_num;i++)
5244         {
5245                 struct target *target = get_current_target(CMD_CTX);
5246                 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
5247                                           (unsigned int)(fastload[i].address),
5248                                           (unsigned int)(fastload[i].length));
5249                 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5250                 if (retval != ERROR_OK)
5251                 {
5252                         break;
5253                 }
5254                 size += fastload[i].length;
5255         }
5256         if (retval == ERROR_OK)
5257         {
5258                 int after = timeval_ms();
5259                 command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5260         }
5261         return retval;
5262 }
5263
5264 static const struct command_registration target_command_handlers[] = {
5265         {
5266                 .name = "targets",
5267                 .handler = handle_targets_command,
5268                 .mode = COMMAND_ANY,
5269                 .help = "change current default target (one parameter) "
5270                         "or prints table of all targets (no parameters)",
5271                 .usage = "[target]",
5272         },
5273         {
5274                 .name = "target",
5275                 .mode = COMMAND_CONFIG,
5276                 .help = "configure target",
5277
5278                 .chain = target_subcommand_handlers,
5279         },
5280         COMMAND_REGISTRATION_DONE
5281 };
5282
5283 int target_register_commands(struct command_context *cmd_ctx)
5284 {
5285         return register_commands(cmd_ctx, NULL, target_command_handlers);
5286 }
5287
5288 static bool target_reset_nag = true;
5289
5290 bool get_target_reset_nag(void)
5291 {
5292         return target_reset_nag;
5293 }
5294
5295 COMMAND_HANDLER(handle_target_reset_nag)
5296 {
5297         return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5298                         &target_reset_nag, "Nag after each reset about options to improve "
5299                         "performance");
5300 }
5301
5302 static const struct command_registration target_exec_command_handlers[] = {
5303         {
5304                 .name = "fast_load_image",
5305                 .handler = handle_fast_load_image_command,
5306                 .mode = COMMAND_ANY,
5307                 .help = "Load image into server memory for later use by "
5308                         "fast_load; primarily for profiling",
5309                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5310                         "[min_address [max_length]]",
5311         },
5312         {
5313                 .name = "fast_load",
5314                 .handler = handle_fast_load_command,
5315                 .mode = COMMAND_EXEC,
5316                 .help = "loads active fast load image to current target "
5317                         "- mainly for profiling purposes",
5318         },
5319         {
5320                 .name = "profile",
5321                 .handler = handle_profile_command,
5322                 .mode = COMMAND_EXEC,
5323                 .help = "profiling samples the CPU PC",
5324         },
5325         /** @todo don't register virt2phys() unless target supports it */
5326         {
5327                 .name = "virt2phys",
5328                 .handler = handle_virt2phys_command,
5329                 .mode = COMMAND_ANY,
5330                 .help = "translate a virtual address into a physical address",
5331                 .usage = "virtual_address",
5332         },
5333         {
5334                 .name = "reg",
5335                 .handler = handle_reg_command,
5336                 .mode = COMMAND_EXEC,
5337                 .help = "display or set a register; with no arguments, "
5338                         "displays all registers and their values",
5339                 .usage = "[(register_name|register_number) [value]]",
5340         },
5341         {
5342                 .name = "poll",
5343                 .handler = handle_poll_command,
5344                 .mode = COMMAND_EXEC,
5345                 .help = "poll target state; or reconfigure background polling",
5346                 .usage = "['on'|'off']",
5347         },
5348         {
5349                 .name = "wait_halt",
5350                 .handler = handle_wait_halt_command,
5351                 .mode = COMMAND_EXEC,
5352                 .help = "wait up to the specified number of milliseconds "
5353                         "(default 5) for a previously requested halt",
5354                 .usage = "[milliseconds]",
5355         },
5356         {
5357                 .name = "halt",
5358                 .handler = handle_halt_command,
5359                 .mode = COMMAND_EXEC,
5360                 .help = "request target to halt, then wait up to the specified"
5361                         "number of milliseconds (default 5) for it to complete",
5362                 .usage = "[milliseconds]",
5363         },
5364         {
5365                 .name = "resume",
5366                 .handler = handle_resume_command,
5367                 .mode = COMMAND_EXEC,
5368                 .help = "resume target execution from current PC or address",
5369                 .usage = "[address]",
5370         },
5371         {
5372                 .name = "reset",
5373                 .handler = handle_reset_command,
5374                 .mode = COMMAND_EXEC,
5375                 .usage = "[run|halt|init]",
5376                 .help = "Reset all targets into the specified mode."
5377                         "Default reset mode is run, if not given.",
5378         },
5379         {
5380                 .name = "soft_reset_halt",
5381                 .handler = handle_soft_reset_halt_command,
5382                 .mode = COMMAND_EXEC,
5383                 .help = "halt the target and do a soft reset",
5384         },
5385         {
5386                 .name = "step",
5387                 .handler = handle_step_command,
5388                 .mode = COMMAND_EXEC,
5389                 .help = "step one instruction from current PC or address",
5390                 .usage = "[address]",
5391         },
5392         {
5393                 .name = "mdw",
5394                 .handler = handle_md_command,
5395                 .mode = COMMAND_EXEC,
5396                 .help = "display memory words",
5397                 .usage = "['phys'] address [count]",
5398         },
5399         {
5400                 .name = "mdh",
5401                 .handler = handle_md_command,
5402                 .mode = COMMAND_EXEC,
5403                 .help = "display memory half-words",
5404                 .usage = "['phys'] address [count]",
5405         },
5406         {
5407                 .name = "mdb",
5408                 .handler = handle_md_command,
5409                 .mode = COMMAND_EXEC,
5410                 .help = "display memory bytes",
5411                 .usage = "['phys'] address [count]",
5412         },
5413         {
5414                 .name = "mww",
5415                 .handler = handle_mw_command,
5416                 .mode = COMMAND_EXEC,
5417                 .help = "write memory word",
5418                 .usage = "['phys'] address value [count]",
5419         },
5420         {
5421                 .name = "mwh",
5422                 .handler = handle_mw_command,
5423                 .mode = COMMAND_EXEC,
5424                 .help = "write memory half-word",
5425                 .usage = "['phys'] address value [count]",
5426         },
5427         {
5428                 .name = "mwb",
5429                 .handler = handle_mw_command,
5430                 .mode = COMMAND_EXEC,
5431                 .help = "write memory byte",
5432                 .usage = "['phys'] address value [count]",
5433         },
5434         {
5435                 .name = "bp",
5436                 .handler = handle_bp_command,
5437                 .mode = COMMAND_EXEC,
5438                 .help = "list or set hardware or software breakpoint",
5439                 .usage = "[address length ['hw']]",
5440         },
5441         {
5442                 .name = "rbp",
5443                 .handler = handle_rbp_command,
5444                 .mode = COMMAND_EXEC,
5445                 .help = "remove breakpoint",
5446                 .usage = "address",
5447         },
5448         {
5449                 .name = "wp",
5450                 .handler = handle_wp_command,
5451                 .mode = COMMAND_EXEC,
5452                 .help = "list (no params) or create watchpoints",
5453                 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
5454         },
5455         {
5456                 .name = "rwp",
5457                 .handler = handle_rwp_command,
5458                 .mode = COMMAND_EXEC,
5459                 .help = "remove watchpoint",
5460                 .usage = "address",
5461         },
5462         {
5463                 .name = "load_image",
5464                 .handler = handle_load_image_command,
5465                 .mode = COMMAND_EXEC,
5466                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
5467                         "[min_address] [max_length]",
5468         },
5469         {
5470                 .name = "dump_image",
5471                 .handler = handle_dump_image_command,
5472                 .mode = COMMAND_EXEC,
5473                 .usage = "filename address size",
5474         },
5475         {
5476                 .name = "verify_image",
5477                 .handler = handle_verify_image_command,
5478                 .mode = COMMAND_EXEC,
5479                 .usage = "filename [offset [type]]",
5480         },
5481         {
5482                 .name = "test_image",
5483                 .handler = handle_test_image_command,
5484                 .mode = COMMAND_EXEC,
5485                 .usage = "filename [offset [type]]",
5486         },
5487         {
5488                 .name = "mem2array",
5489                 .mode = COMMAND_EXEC,
5490                 .jim_handler = jim_mem2array,
5491                 .help = "read 8/16/32 bit memory and return as a TCL array "
5492                         "for script processing",
5493                 .usage = "arrayname bitwidth address count",
5494         },
5495         {
5496                 .name = "array2mem",
5497                 .mode = COMMAND_EXEC,
5498                 .jim_handler = jim_array2mem,
5499                 .help = "convert a TCL array to memory locations "
5500                         "and write the 8/16/32 bit values",
5501                 .usage = "arrayname bitwidth address count",
5502         },
5503         {
5504                 .name = "reset_nag",
5505                 .handler = handle_target_reset_nag,
5506                 .mode = COMMAND_ANY,
5507                 .help = "Nag after each reset about options that could have been "
5508                                 "enabled to improve performance. ",
5509                 .usage = "['enable'|'disable']",
5510         },
5511         COMMAND_REGISTRATION_DONE
5512 };
5513 static int target_register_user_commands(struct command_context *cmd_ctx)
5514 {
5515         int retval = ERROR_OK;
5516         if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5517                 return retval;
5518
5519         if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5520                 return retval;
5521
5522
5523         return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
5524 }