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