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