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