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