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