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