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