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