lm32: initial version (somehow working)
[mw/openocd-lm32.git] / src / target / target.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007-2010 √ėyvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   Copyright (C) 2008, Duane Ellis                                       *
9  *   openocd@duaneeellis.com                                               *
10  *                                                                         *
11  *   Copyright (C) 2008 by Spencer Oliver                                  *
12  *   spen@spen-soft.co.uk                                                  *
13  *                                                                         *
14  *   Copyright (C) 2008 by Rick Altherr                                    *
15  *   kc8apf@kc8apf.net>                                                    *
16  *                                                                         *
17  *   This program is free software; you can redistribute it and/or modify  *
18  *   it under the terms of the GNU General Public License as published by  *
19  *   the Free Software Foundation; either version 2 of the License, or     *
20  *   (at your option) any later version.                                   *
21  *                                                                         *
22  *   This program is distributed in the hope that it will be useful,       *
23  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
24  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
25  *   GNU General Public License for more details.                          *
26  *                                                                         *
27  *   You should have received a copy of the GNU General Public License     *
28  *   along with this program; if not, write to the                         *
29  *   Free Software Foundation, Inc.,                                       *
30  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
31  ***************************************************************************/
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
35
36 #include <helper/time_support.h>
37 #include <jtag/jtag.h>
38 #include <flash/nor/core.h>
39
40 #include "target.h"
41 #include "target_type.h"
42 #include "target_request.h"
43 #include "breakpoints.h"
44 #include "register.h"
45 #include "trace.h"
46 #include "image.h"
47
48
49 static int target_array2mem(Jim_Interp *interp, struct target *target,
50                 int argc, Jim_Obj *const *argv);
51 static int target_mem2array(Jim_Interp *interp, struct target *target,
52                 int argc, Jim_Obj *const *argv);
53 static int target_register_user_commands(struct command_context *cmd_ctx);
54
55 /* targets */
56 extern struct target_type arm7tdmi_target;
57 extern struct target_type arm720t_target;
58 extern struct target_type arm9tdmi_target;
59 extern struct target_type arm920t_target;
60 extern struct target_type arm966e_target;
61 extern struct target_type arm926ejs_target;
62 extern struct target_type fa526_target;
63 extern struct target_type feroceon_target;
64 extern struct target_type dragonite_target;
65 extern struct target_type xscale_target;
66 extern struct target_type cortexm3_target;
67 extern struct target_type cortexa8_target;
68 extern struct target_type arm11_target;
69 extern struct target_type mips_m4k_target;
70 extern struct target_type avr_target;
71 extern struct target_type dsp563xx_target;
72 extern struct target_type testee_target;
73 extern struct target_type avr32_ap7k_target;
74 extern struct target_type lm32_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         &arm926ejs_target,
84         &fa526_target,
85         &feroceon_target,
86         &dragonite_target,
87         &xscale_target,
88         &cortexm3_target,
89         &cortexa8_target,
90         &arm11_target,
91         &mips_m4k_target,
92         &avr_target,
93         &dsp563xx_target,
94         &testee_target,
95         &avr32_ap7k_target,
96         &lm32_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_PrintErrorMessage(cmd_ctx->interp);
511                 return ERROR_FAIL;
512         }
513
514         /* We want any events to be processed before the prompt */
515         retval = target_call_timer_callbacks_now();
516
517         struct target *target;
518         for (target = all_targets; target; target = target->next) {
519                 target->type->check_reset(target);
520         }
521
522         return retval;
523 }
524
525 static int identity_virt2phys(struct target *target,
526                 uint32_t virtual, uint32_t *physical)
527 {
528         *physical = virtual;
529         return ERROR_OK;
530 }
531
532 static int no_mmu(struct target *target, int *enabled)
533 {
534         *enabled = 0;
535         return ERROR_OK;
536 }
537
538 static int default_examine(struct target *target)
539 {
540         target_set_examined(target);
541         return ERROR_OK;
542 }
543
544 /* no check by default */
545 static int default_check_reset(struct target *target)
546 {
547         return ERROR_OK;
548 }
549
550 int target_examine_one(struct target *target)
551 {
552         return target->type->examine(target);
553 }
554
555 static int jtag_enable_callback(enum jtag_event event, void *priv)
556 {
557         struct target *target = priv;
558
559         if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
560                 return ERROR_OK;
561
562         jtag_unregister_event_callback(jtag_enable_callback, target);
563         return target_examine_one(target);
564 }
565
566
567 /* Targets that correctly implement init + examine, i.e.
568  * no communication with target during init:
569  *
570  * XScale
571  */
572 int target_examine(void)
573 {
574         int retval = ERROR_OK;
575         struct target *target;
576
577         for (target = all_targets; target; target = target->next)
578         {
579                 /* defer examination, but don't skip it */
580                 if (!target->tap->enabled) {
581                         jtag_register_event_callback(jtag_enable_callback,
582                                         target);
583                         continue;
584                 }
585                 if ((retval = target_examine_one(target)) != ERROR_OK)
586                         return retval;
587         }
588         return retval;
589 }
590 const char *target_type_name(struct target *target)
591 {
592         return target->type->name;
593 }
594
595 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
596 {
597         if (!target_was_examined(target))
598         {
599                 LOG_ERROR("Target not examined yet");
600                 return ERROR_FAIL;
601         }
602         return target->type->write_memory_imp(target, address, size, count, buffer);
603 }
604
605 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
606 {
607         if (!target_was_examined(target))
608         {
609                 LOG_ERROR("Target not examined yet");
610                 return ERROR_FAIL;
611         }
612         return target->type->read_memory_imp(target, address, size, count, buffer);
613 }
614
615 static int target_soft_reset_halt_imp(struct target *target)
616 {
617         if (!target_was_examined(target))
618         {
619                 LOG_ERROR("Target not examined yet");
620                 return ERROR_FAIL;
621         }
622         if (!target->type->soft_reset_halt_imp) {
623                 LOG_ERROR("Target %s does not support soft_reset_halt",
624                                 target_name(target));
625                 return ERROR_FAIL;
626         }
627         return target->type->soft_reset_halt_imp(target);
628 }
629
630 /**
631  * Downloads a target-specific native code algorithm to the target,
632  * and executes it.  * Note that some targets may need to set up, enable,
633  * and tear down a breakpoint (hard or * soft) to detect algorithm
634  * termination, while others may support  lower overhead schemes where
635  * soft breakpoints embedded in the algorithm automatically terminate the
636  * algorithm.
637  *
638  * @param target used to run the algorithm
639  * @param arch_info target-specific description of the algorithm.
640  */
641 int target_run_algorithm(struct target *target,
642                 int num_mem_params, struct mem_param *mem_params,
643                 int num_reg_params, struct reg_param *reg_param,
644                 uint32_t entry_point, uint32_t exit_point,
645                 int timeout_ms, void *arch_info)
646 {
647         int retval = ERROR_FAIL;
648
649         if (!target_was_examined(target))
650         {
651                 LOG_ERROR("Target not examined yet");
652                 goto done;
653         }
654         if (!target->type->run_algorithm) {
655                 LOG_ERROR("Target type '%s' does not support %s",
656                                 target_type_name(target), __func__);
657                 goto done;
658         }
659
660         target->running_alg = true;
661         retval = target->type->run_algorithm(target,
662                         num_mem_params, mem_params,
663                         num_reg_params, reg_param,
664                         entry_point, exit_point, timeout_ms, arch_info);
665         target->running_alg = false;
666
667 done:
668         return retval;
669 }
670
671
672 int target_read_memory(struct target *target,
673                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
674 {
675         return target->type->read_memory(target, address, size, count, buffer);
676 }
677
678 static int target_read_phys_memory(struct target *target,
679                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
680 {
681         return target->type->read_phys_memory(target, address, size, count, buffer);
682 }
683
684 int target_write_memory(struct target *target,
685                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
686 {
687         return target->type->write_memory(target, address, size, count, buffer);
688 }
689
690 static int target_write_phys_memory(struct target *target,
691                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
692 {
693         return target->type->write_phys_memory(target, address, size, count, buffer);
694 }
695
696 int target_bulk_write_memory(struct target *target,
697                 uint32_t address, uint32_t count, uint8_t *buffer)
698 {
699         return target->type->bulk_write_memory(target, address, count, buffer);
700 }
701
702 int target_add_breakpoint(struct target *target,
703                 struct breakpoint *breakpoint)
704 {
705         if (target->state != TARGET_HALTED) {
706                 LOG_WARNING("target %s is not halted", target->cmd_name);
707                 return ERROR_TARGET_NOT_HALTED;
708         }
709         return target->type->add_breakpoint(target, breakpoint);
710 }
711 int target_remove_breakpoint(struct target *target,
712                 struct breakpoint *breakpoint)
713 {
714         return target->type->remove_breakpoint(target, breakpoint);
715 }
716
717 int target_add_watchpoint(struct target *target,
718                 struct watchpoint *watchpoint)
719 {
720         if (target->state != TARGET_HALTED) {
721                 LOG_WARNING("target %s is not halted", target->cmd_name);
722                 return ERROR_TARGET_NOT_HALTED;
723         }
724         return target->type->add_watchpoint(target, watchpoint);
725 }
726 int target_remove_watchpoint(struct target *target,
727                 struct watchpoint *watchpoint)
728 {
729         return target->type->remove_watchpoint(target, watchpoint);
730 }
731
732 int target_get_gdb_reg_list(struct target *target,
733                 struct reg **reg_list[], int *reg_list_size)
734 {
735         return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
736 }
737 int target_step(struct target *target,
738                 int current, uint32_t address, int handle_breakpoints)
739 {
740         return target->type->step(target, current, address, handle_breakpoints);
741 }
742
743
744 /**
745  * Reset the @c examined flag for the given target.
746  * Pure paranoia -- targets are zeroed on allocation.
747  */
748 static void target_reset_examined(struct target *target)
749 {
750         target->examined = false;
751 }
752
753 static int
754 err_read_phys_memory(struct target *target, uint32_t address,
755                 uint32_t size, uint32_t count, uint8_t *buffer)
756 {
757         LOG_ERROR("Not implemented: %s", __func__);
758         return ERROR_FAIL;
759 }
760
761 static int
762 err_write_phys_memory(struct target *target, uint32_t address,
763                 uint32_t size, uint32_t count, uint8_t *buffer)
764 {
765         LOG_ERROR("Not implemented: %s", __func__);
766         return ERROR_FAIL;
767 }
768
769 static int handle_target(void *priv);
770
771 static int target_init_one(struct command_context *cmd_ctx,
772                 struct target *target)
773 {
774         target_reset_examined(target);
775
776         struct target_type *type = target->type;
777         if (type->examine == NULL)
778                 type->examine = default_examine;
779
780         if (type->check_reset== NULL)
781                 type->check_reset = default_check_reset;
782
783         int retval = type->init_target(cmd_ctx, target);
784         if (ERROR_OK != retval)
785         {
786                 LOG_ERROR("target '%s' init failed", target_name(target));
787                 return retval;
788         }
789
790         /**
791          * @todo get rid of those *memory_imp() methods, now that all
792          * callers are using target_*_memory() accessors ... and make
793          * sure the "physical" paths handle the same issues.
794          */
795         /* a non-invasive way(in terms of patches) to add some code that
796          * runs before the type->write/read_memory implementation
797          */
798         type->write_memory_imp = target->type->write_memory;
799         type->write_memory = target_write_memory_imp;
800
801         type->read_memory_imp = target->type->read_memory;
802         type->read_memory = target_read_memory_imp;
803
804         type->soft_reset_halt_imp = target->type->soft_reset_halt;
805         type->soft_reset_halt = target_soft_reset_halt_imp;
806
807         /* Sanity-check MMU support ... stub in what we must, to help
808          * implement it in stages, but warn if we need to do so.
809          */
810         if (type->mmu)
811         {
812                 if (type->write_phys_memory == NULL)
813                 {
814                         LOG_ERROR("type '%s' is missing write_phys_memory",
815                                         type->name);
816                         type->write_phys_memory = err_write_phys_memory;
817                 }
818                 if (type->read_phys_memory == NULL)
819                 {
820                         LOG_ERROR("type '%s' is missing read_phys_memory",
821                                         type->name);
822                         type->read_phys_memory = err_read_phys_memory;
823                 }
824                 if (type->virt2phys == NULL)
825                 {
826                         LOG_ERROR("type '%s' is missing virt2phys", type->name);
827                         type->virt2phys = identity_virt2phys;
828                 }
829         }
830         else
831         {
832                 /* Make sure no-MMU targets all behave the same:  make no
833                  * distinction between physical and virtual addresses, and
834                  * ensure that virt2phys() is always an identity mapping.
835                  */
836                 if (type->write_phys_memory || type->read_phys_memory
837                                 || type->virt2phys)
838                 {
839                         LOG_WARNING("type '%s' has bad MMU hooks", type->name);
840                 }
841
842                 type->mmu = no_mmu;
843                 type->write_phys_memory = type->write_memory;
844                 type->read_phys_memory = type->read_memory;
845                 type->virt2phys = identity_virt2phys;
846         }
847         return ERROR_OK;
848 }
849
850 static int target_init(struct command_context *cmd_ctx)
851 {
852         struct target *target;
853         int retval;
854
855         for (target = all_targets; target; target = target->next)
856         {
857                 retval = target_init_one(cmd_ctx, target);
858                 if (ERROR_OK != retval)
859                         return retval;
860         }
861
862         if (!all_targets)
863                 return ERROR_OK;
864
865         retval = target_register_user_commands(cmd_ctx);
866         if (ERROR_OK != retval)
867                 return retval;
868
869         retval = target_register_timer_callback(&handle_target,
870                         polling_interval, 1, cmd_ctx->interp);
871         if (ERROR_OK != retval)
872                 return retval;
873
874         return ERROR_OK;
875 }
876
877 COMMAND_HANDLER(handle_target_init_command)
878 {
879         if (CMD_ARGC != 0)
880                 return ERROR_COMMAND_SYNTAX_ERROR;
881
882         static bool target_initialized = false;
883         if (target_initialized)
884         {
885                 LOG_INFO("'target init' has already been called");
886                 return ERROR_OK;
887         }
888         target_initialized = true;
889
890         LOG_DEBUG("Initializing targets...");
891         return target_init(CMD_CTX);
892 }
893
894 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
895 {
896         struct target_event_callback **callbacks_p = &target_event_callbacks;
897
898         if (callback == NULL)
899         {
900                 return ERROR_INVALID_ARGUMENTS;
901         }
902
903         if (*callbacks_p)
904         {
905                 while ((*callbacks_p)->next)
906                         callbacks_p = &((*callbacks_p)->next);
907                 callbacks_p = &((*callbacks_p)->next);
908         }
909
910         (*callbacks_p) = malloc(sizeof(struct target_event_callback));
911         (*callbacks_p)->callback = callback;
912         (*callbacks_p)->priv = priv;
913         (*callbacks_p)->next = NULL;
914
915         return ERROR_OK;
916 }
917
918 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
919 {
920         struct target_timer_callback **callbacks_p = &target_timer_callbacks;
921         struct timeval now;
922
923         if (callback == NULL)
924         {
925                 return ERROR_INVALID_ARGUMENTS;
926         }
927
928         if (*callbacks_p)
929         {
930                 while ((*callbacks_p)->next)
931                         callbacks_p = &((*callbacks_p)->next);
932                 callbacks_p = &((*callbacks_p)->next);
933         }
934
935         (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
936         (*callbacks_p)->callback = callback;
937         (*callbacks_p)->periodic = periodic;
938         (*callbacks_p)->time_ms = time_ms;
939
940         gettimeofday(&now, NULL);
941         (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
942         time_ms -= (time_ms % 1000);
943         (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
944         if ((*callbacks_p)->when.tv_usec > 1000000)
945         {
946                 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
947                 (*callbacks_p)->when.tv_sec += 1;
948         }
949
950         (*callbacks_p)->priv = priv;
951         (*callbacks_p)->next = NULL;
952
953         return ERROR_OK;
954 }
955
956 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
957 {
958         struct target_event_callback **p = &target_event_callbacks;
959         struct target_event_callback *c = target_event_callbacks;
960
961         if (callback == NULL)
962         {
963                 return ERROR_INVALID_ARGUMENTS;
964         }
965
966         while (c)
967         {
968                 struct target_event_callback *next = c->next;
969                 if ((c->callback == callback) && (c->priv == priv))
970                 {
971                         *p = next;
972                         free(c);
973                         return ERROR_OK;
974                 }
975                 else
976                         p = &(c->next);
977                 c = next;
978         }
979
980         return ERROR_OK;
981 }
982
983 static int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
984 {
985         struct target_timer_callback **p = &target_timer_callbacks;
986         struct target_timer_callback *c = target_timer_callbacks;
987
988         if (callback == NULL)
989         {
990                 return ERROR_INVALID_ARGUMENTS;
991         }
992
993         while (c)
994         {
995                 struct target_timer_callback *next = c->next;
996                 if ((c->callback == callback) && (c->priv == priv))
997                 {
998                         *p = next;
999                         free(c);
1000                         return ERROR_OK;
1001                 }
1002                 else
1003                         p = &(c->next);
1004                 c = next;
1005         }
1006
1007         return ERROR_OK;
1008 }
1009
1010 int target_call_event_callbacks(struct target *target, enum target_event event)
1011 {
1012         struct target_event_callback *callback = target_event_callbacks;
1013         struct target_event_callback *next_callback;
1014
1015         if (event == TARGET_EVENT_HALTED)
1016         {
1017                 /* execute early halted first */
1018                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1019         }
1020
1021         LOG_DEBUG("target event %i (%s)",
1022                           event,
1023                           Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1024
1025         target_handle_event(target, event);
1026
1027         while (callback)
1028         {
1029                 next_callback = callback->next;
1030                 callback->callback(target, event, callback->priv);
1031                 callback = next_callback;
1032         }
1033
1034         return ERROR_OK;
1035 }
1036
1037 static int target_timer_callback_periodic_restart(
1038                 struct target_timer_callback *cb, struct timeval *now)
1039 {
1040         int time_ms = cb->time_ms;
1041         cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1042         time_ms -= (time_ms % 1000);
1043         cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1044         if (cb->when.tv_usec > 1000000)
1045         {
1046                 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1047                 cb->when.tv_sec += 1;
1048         }
1049         return ERROR_OK;
1050 }
1051
1052 static int target_call_timer_callback(struct target_timer_callback *cb,
1053                 struct timeval *now)
1054 {
1055         cb->callback(cb->priv);
1056
1057         if (cb->periodic)
1058                 return target_timer_callback_periodic_restart(cb, now);
1059
1060         return target_unregister_timer_callback(cb->callback, cb->priv);
1061 }
1062
1063 static int target_call_timer_callbacks_check_time(int checktime)
1064 {
1065         keep_alive();
1066
1067         struct timeval now;
1068         gettimeofday(&now, NULL);
1069
1070         struct target_timer_callback *callback = target_timer_callbacks;
1071         while (callback)
1072         {
1073                 // cleaning up may unregister and free this callback
1074                 struct target_timer_callback *next_callback = callback->next;
1075
1076                 bool call_it = callback->callback &&
1077                         ((!checktime && callback->periodic) ||
1078                           now.tv_sec > callback->when.tv_sec ||
1079                          (now.tv_sec == callback->when.tv_sec &&
1080                           now.tv_usec >= callback->when.tv_usec));
1081
1082                 if (call_it)
1083                 {
1084                         int retval = target_call_timer_callback(callback, &now);
1085                         if (retval != ERROR_OK)
1086                                 return retval;
1087                 }
1088
1089                 callback = next_callback;
1090         }
1091
1092         return ERROR_OK;
1093 }
1094
1095 int target_call_timer_callbacks(void)
1096 {
1097         return target_call_timer_callbacks_check_time(1);
1098 }
1099
1100 /* invoke periodic callbacks immediately */
1101 int target_call_timer_callbacks_now(void)
1102 {
1103         return target_call_timer_callbacks_check_time(0);
1104 }
1105
1106 int target_alloc_working_area_try(struct target *target, uint32_t size, struct working_area **area)
1107 {
1108         struct working_area *c = target->working_areas;
1109         struct working_area *new_wa = NULL;
1110
1111         /* Reevaluate working area address based on MMU state*/
1112         if (target->working_areas == NULL)
1113         {
1114                 int retval;
1115                 int enabled;
1116
1117                 retval = target->type->mmu(target, &enabled);
1118                 if (retval != ERROR_OK)
1119                 {
1120                         return retval;
1121                 }
1122
1123                 if (!enabled) {
1124                         if (target->working_area_phys_spec) {
1125                                 LOG_DEBUG("MMU disabled, using physical "
1126                                         "address for working memory 0x%08x",
1127                                         (unsigned)target->working_area_phys);
1128                                 target->working_area = target->working_area_phys;
1129                         } else {
1130                                 LOG_ERROR("No working memory available. "
1131                                         "Specify -work-area-phys to target.");
1132                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1133                         }
1134                 } else {
1135                         if (target->working_area_virt_spec) {
1136                                 LOG_DEBUG("MMU enabled, using virtual "
1137                                         "address for working memory 0x%08x",
1138                                         (unsigned)target->working_area_virt);
1139                                 target->working_area = target->working_area_virt;
1140                         } else {
1141                                 LOG_ERROR("No working memory available. "
1142                                         "Specify -work-area-virt to target.");
1143                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1144                         }
1145                 }
1146         }
1147
1148         /* only allocate multiples of 4 byte */
1149         if (size % 4)
1150         {
1151                 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1152                 size = (size + 3) & (~3);
1153         }
1154
1155         /* see if there's already a matching working area */
1156         while (c)
1157         {
1158                 if ((c->free) && (c->size == size))
1159                 {
1160                         new_wa = c;
1161                         break;
1162                 }
1163                 c = c->next;
1164         }
1165
1166         /* if not, allocate a new one */
1167         if (!new_wa)
1168         {
1169                 struct working_area **p = &target->working_areas;
1170                 uint32_t first_free = target->working_area;
1171                 uint32_t free_size = target->working_area_size;
1172
1173                 c = target->working_areas;
1174                 while (c)
1175                 {
1176                         first_free += c->size;
1177                         free_size -= c->size;
1178                         p = &c->next;
1179                         c = c->next;
1180                 }
1181
1182                 if (free_size < size)
1183                 {
1184                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1185                 }
1186
1187                 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1188
1189                 new_wa = malloc(sizeof(struct working_area));
1190                 new_wa->next = NULL;
1191                 new_wa->size = size;
1192                 new_wa->address = first_free;
1193
1194                 if (target->backup_working_area)
1195                 {
1196                         int retval;
1197                         new_wa->backup = malloc(new_wa->size);
1198                         if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1199                         {
1200                                 free(new_wa->backup);
1201                                 free(new_wa);
1202                                 return retval;
1203                         }
1204                 }
1205                 else
1206                 {
1207                         new_wa->backup = NULL;
1208                 }
1209
1210                 /* put new entry in list */
1211                 *p = new_wa;
1212         }
1213
1214         /* mark as used, and return the new (reused) area */
1215         new_wa->free = 0;
1216         *area = new_wa;
1217
1218         /* user pointer */
1219         new_wa->user = area;
1220
1221         return ERROR_OK;
1222 }
1223
1224 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
1225 {
1226         int retval;
1227
1228         retval = target_alloc_working_area_try(target, size, area);
1229         if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1230         {
1231                 LOG_WARNING("not enough working area available(requested %u)", (unsigned)(size));
1232         }
1233         return retval;
1234
1235 }
1236
1237 static int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1238 {
1239         if (area->free)
1240                 return ERROR_OK;
1241
1242         if (restore && target->backup_working_area)
1243         {
1244                 int retval;
1245                 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1246                         return retval;
1247         }
1248
1249         area->free = 1;
1250
1251         /* mark user pointer invalid */
1252         *area->user = NULL;
1253         area->user = NULL;
1254
1255         return ERROR_OK;
1256 }
1257
1258 int target_free_working_area(struct target *target, struct working_area *area)
1259 {
1260         return target_free_working_area_restore(target, area, 1);
1261 }
1262
1263 /* free resources and restore memory, if restoring memory fails,
1264  * free up resources anyway
1265  */
1266 static void target_free_all_working_areas_restore(struct target *target, int restore)
1267 {
1268         struct working_area *c = target->working_areas;
1269
1270         while (c)
1271         {
1272                 struct working_area *next = c->next;
1273                 target_free_working_area_restore(target, c, restore);
1274
1275                 if (c->backup)
1276                         free(c->backup);
1277
1278                 free(c);
1279
1280                 c = next;
1281         }
1282
1283         target->working_areas = NULL;
1284 }
1285
1286 void target_free_all_working_areas(struct target *target)
1287 {
1288         target_free_all_working_areas_restore(target, 1);
1289 }
1290
1291 int target_arch_state(struct target *target)
1292 {
1293         int retval;
1294         if (target == NULL)
1295         {
1296                 LOG_USER("No target has been configured");
1297                 return ERROR_OK;
1298         }
1299
1300         LOG_USER("target state: %s", target_state_name( target ));
1301
1302         if (target->state != TARGET_HALTED)
1303                 return ERROR_OK;
1304
1305         retval = target->type->arch_state(target);
1306         return retval;
1307 }
1308
1309 /* Single aligned words are guaranteed to use 16 or 32 bit access
1310  * mode respectively, otherwise data is handled as quickly as
1311  * possible
1312  */
1313 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1314 {
1315         int retval;
1316         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1317                   (int)size, (unsigned)address);
1318
1319         if (!target_was_examined(target))
1320         {
1321                 LOG_ERROR("Target not examined yet");
1322                 return ERROR_FAIL;
1323         }
1324
1325         if (size == 0) {
1326                 return ERROR_OK;
1327         }
1328
1329         if ((address + size - 1) < address)
1330         {
1331                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1332                 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1333                                   (unsigned)address,
1334                                   (unsigned)size);
1335                 return ERROR_FAIL;
1336         }
1337
1338         if (((address % 2) == 0) && (size == 2))
1339         {
1340                 return target_write_memory(target, address, 2, 1, buffer);
1341         }
1342
1343         /* handle unaligned head bytes */
1344         if (address % 4)
1345         {
1346                 uint32_t unaligned = 4 - (address % 4);
1347
1348                 if (unaligned > size)
1349                         unaligned = size;
1350
1351                 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1352                         return retval;
1353
1354                 buffer += unaligned;
1355                 address += unaligned;
1356                 size -= unaligned;
1357         }
1358
1359         /* handle aligned words */
1360         if (size >= 4)
1361         {
1362                 int aligned = size - (size % 4);
1363
1364                 /* use bulk writes above a certain limit. This may have to be changed */
1365                 if (aligned > 128)
1366                 {
1367                         if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1368                                 return retval;
1369                 }
1370                 else
1371                 {
1372                         if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1373                                 return retval;
1374                 }
1375
1376                 buffer += aligned;
1377                 address += aligned;
1378                 size -= aligned;
1379         }
1380
1381         /* handle tail writes of less than 4 bytes */
1382         if (size > 0)
1383         {
1384                 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1385                         return retval;
1386         }
1387
1388         return ERROR_OK;
1389 }
1390
1391 /* Single aligned words are guaranteed to use 16 or 32 bit access
1392  * mode respectively, otherwise data is handled as quickly as
1393  * possible
1394  */
1395 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1396 {
1397         int retval;
1398         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1399                           (int)size, (unsigned)address);
1400
1401         if (!target_was_examined(target))
1402         {
1403                 LOG_ERROR("Target not examined yet");
1404                 return ERROR_FAIL;
1405         }
1406
1407         if (size == 0) {
1408                 return ERROR_OK;
1409         }
1410
1411         if ((address + size - 1) < address)
1412         {
1413                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1414                 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1415                                   address,
1416                                   size);
1417                 return ERROR_FAIL;
1418         }
1419
1420         if (((address % 2) == 0) && (size == 2))
1421         {
1422                 return target_read_memory(target, address, 2, 1, buffer);
1423         }
1424
1425         /* handle unaligned head bytes */
1426         if (address % 4)
1427         {
1428                 uint32_t unaligned = 4 - (address % 4);
1429
1430                 if (unaligned > size)
1431                         unaligned = size;
1432
1433                 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1434                         return retval;
1435
1436                 buffer += unaligned;
1437                 address += unaligned;
1438                 size -= unaligned;
1439         }
1440
1441         /* handle aligned words */
1442         if (size >= 4)
1443         {
1444                 int aligned = size - (size % 4);
1445
1446                 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1447                         return retval;
1448
1449                 buffer += aligned;
1450                 address += aligned;
1451                 size -= aligned;
1452         }
1453
1454         /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1455         if(size >=2)
1456         {
1457                 int aligned = size - (size%2);
1458                 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1459                 if (retval != ERROR_OK)
1460                         return retval;
1461
1462                 buffer += aligned;
1463                 address += aligned;
1464                 size -= aligned;
1465         }
1466         /* handle tail writes of less than 4 bytes */
1467         if (size > 0)
1468         {
1469                 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1470                         return retval;
1471         }
1472
1473         return ERROR_OK;
1474 }
1475
1476 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1477 {
1478         uint8_t *buffer;
1479         int retval;
1480         uint32_t i;
1481         uint32_t checksum = 0;
1482         if (!target_was_examined(target))
1483         {
1484                 LOG_ERROR("Target not examined yet");
1485                 return ERROR_FAIL;
1486         }
1487
1488         if ((retval = target->type->checksum_memory(target, address,
1489                 size, &checksum)) != ERROR_OK)
1490         {
1491                 buffer = malloc(size);
1492                 if (buffer == NULL)
1493                 {
1494                         LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1495                         return ERROR_INVALID_ARGUMENTS;
1496                 }
1497                 retval = target_read_buffer(target, address, size, buffer);
1498                 if (retval != ERROR_OK)
1499                 {
1500                         free(buffer);
1501                         return retval;
1502                 }
1503
1504                 /* convert to target endianess */
1505                 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1506                 {
1507                         uint32_t target_data;
1508                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1509                         target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1510                 }
1511
1512                 retval = image_calculate_checksum(buffer, size, &checksum);
1513                 free(buffer);
1514         }
1515
1516         *crc = checksum;
1517
1518         return retval;
1519 }
1520
1521 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1522 {
1523         int retval;
1524         if (!target_was_examined(target))
1525         {
1526                 LOG_ERROR("Target not examined yet");
1527                 return ERROR_FAIL;
1528         }
1529
1530         if (target->type->blank_check_memory == 0)
1531                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1532
1533         retval = target->type->blank_check_memory(target, address, size, blank);
1534
1535         return retval;
1536 }
1537
1538 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1539 {
1540         uint8_t value_buf[4];
1541         if (!target_was_examined(target))
1542         {
1543                 LOG_ERROR("Target not examined yet");
1544                 return ERROR_FAIL;
1545         }
1546
1547         int retval = target_read_memory(target, address, 4, 1, value_buf);
1548
1549         if (retval == ERROR_OK)
1550         {
1551                 *value = target_buffer_get_u32(target, value_buf);
1552                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1553                                   address,
1554                                   *value);
1555         }
1556         else
1557         {
1558                 *value = 0x0;
1559                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1560                                   address);
1561         }
1562
1563         return retval;
1564 }
1565
1566 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1567 {
1568         uint8_t value_buf[2];
1569         if (!target_was_examined(target))
1570         {
1571                 LOG_ERROR("Target not examined yet");
1572                 return ERROR_FAIL;
1573         }
1574
1575         int retval = target_read_memory(target, address, 2, 1, value_buf);
1576
1577         if (retval == ERROR_OK)
1578         {
1579                 *value = target_buffer_get_u16(target, value_buf);
1580                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1581                                   address,
1582                                   *value);
1583         }
1584         else
1585         {
1586                 *value = 0x0;
1587                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1588                                   address);
1589         }
1590
1591         return retval;
1592 }
1593
1594 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1595 {
1596         int retval = target_read_memory(target, address, 1, 1, value);
1597         if (!target_was_examined(target))
1598         {
1599                 LOG_ERROR("Target not examined yet");
1600                 return ERROR_FAIL;
1601         }
1602
1603         if (retval == ERROR_OK)
1604         {
1605                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1606                                   address,
1607                                   *value);
1608         }
1609         else
1610         {
1611                 *value = 0x0;
1612                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1613                                   address);
1614         }
1615
1616         return retval;
1617 }
1618
1619 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1620 {
1621         int retval;
1622         uint8_t value_buf[4];
1623         if (!target_was_examined(target))
1624         {
1625                 LOG_ERROR("Target not examined yet");
1626                 return ERROR_FAIL;
1627         }
1628
1629         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1630                           address,
1631                           value);
1632
1633         target_buffer_set_u32(target, value_buf, value);
1634         if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1635         {
1636                 LOG_DEBUG("failed: %i", retval);
1637         }
1638
1639         return retval;
1640 }
1641
1642 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1643 {
1644         int retval;
1645         uint8_t value_buf[2];
1646         if (!target_was_examined(target))
1647         {
1648                 LOG_ERROR("Target not examined yet");
1649                 return ERROR_FAIL;
1650         }
1651
1652         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1653                           address,
1654                           value);
1655
1656         target_buffer_set_u16(target, value_buf, value);
1657         if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1658         {
1659                 LOG_DEBUG("failed: %i", retval);
1660         }
1661
1662         return retval;
1663 }
1664
1665 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1666 {
1667         int retval;
1668         if (!target_was_examined(target))
1669         {
1670                 LOG_ERROR("Target not examined yet");
1671                 return ERROR_FAIL;
1672         }
1673
1674         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1675                           address, value);
1676
1677         if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1678         {
1679                 LOG_DEBUG("failed: %i", retval);
1680         }
1681
1682         return retval;
1683 }
1684
1685 COMMAND_HANDLER(handle_targets_command)
1686 {
1687         struct target *target = all_targets;
1688
1689         if (CMD_ARGC == 1)
1690         {
1691                 target = get_target(CMD_ARGV[0]);
1692                 if (target == NULL) {
1693                         command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1694                         goto DumpTargets;
1695                 }
1696                 if (!target->tap->enabled) {
1697                         command_print(CMD_CTX,"Target: TAP %s is disabled, "
1698                                         "can't be the current target\n",
1699                                         target->tap->dotted_name);
1700                         return ERROR_FAIL;
1701                 }
1702
1703                 CMD_CTX->current_target = target->target_number;
1704                 return ERROR_OK;
1705         }
1706 DumpTargets:
1707
1708         target = all_targets;
1709         command_print(CMD_CTX, "    TargetName         Type       Endian TapName            State       ");
1710         command_print(CMD_CTX, "--  ------------------ ---------- ------ ------------------ ------------");
1711         while (target)
1712         {
1713                 const char *state;
1714                 char marker = ' ';
1715
1716                 if (target->tap->enabled)
1717                         state = target_state_name( target );
1718                 else
1719                         state = "tap-disabled";
1720
1721                 if (CMD_CTX->current_target == target->target_number)
1722                         marker = '*';
1723
1724                 /* keep columns lined up to match the headers above */
1725                 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1726                                           target->target_number,
1727                                           marker,
1728                                           target_name(target),
1729                                           target_type_name(target),
1730                                           Jim_Nvp_value2name_simple(nvp_target_endian,
1731                                                                 target->endianness)->name,
1732                                           target->tap->dotted_name,
1733                                           state);
1734                 target = target->next;
1735         }
1736
1737         return ERROR_OK;
1738 }
1739
1740 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1741
1742 static int powerDropout;
1743 static int srstAsserted;
1744
1745 static int runPowerRestore;
1746 static int runPowerDropout;
1747 static int runSrstAsserted;
1748 static int runSrstDeasserted;
1749
1750 static int sense_handler(void)
1751 {
1752         static int prevSrstAsserted = 0;
1753         static int prevPowerdropout = 0;
1754
1755         int retval;
1756         if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1757                 return retval;
1758
1759         int powerRestored;
1760         powerRestored = prevPowerdropout && !powerDropout;
1761         if (powerRestored)
1762         {
1763                 runPowerRestore = 1;
1764         }
1765
1766         long long current = timeval_ms();
1767         static long long lastPower = 0;
1768         int waitMore = lastPower + 2000 > current;
1769         if (powerDropout && !waitMore)
1770         {
1771                 runPowerDropout = 1;
1772                 lastPower = current;
1773         }
1774
1775         if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1776                 return retval;
1777
1778         int srstDeasserted;
1779         srstDeasserted = prevSrstAsserted && !srstAsserted;
1780
1781         static long long lastSrst = 0;
1782         waitMore = lastSrst + 2000 > current;
1783         if (srstDeasserted && !waitMore)
1784         {
1785                 runSrstDeasserted = 1;
1786                 lastSrst = current;
1787         }
1788
1789         if (!prevSrstAsserted && srstAsserted)
1790         {
1791                 runSrstAsserted = 1;
1792         }
1793
1794         prevSrstAsserted = srstAsserted;
1795         prevPowerdropout = powerDropout;
1796
1797         if (srstDeasserted || powerRestored)
1798         {
1799                 /* Other than logging the event we can't do anything here.
1800                  * Issuing a reset is a particularly bad idea as we might
1801                  * be inside a reset already.
1802                  */
1803         }
1804
1805         return ERROR_OK;
1806 }
1807
1808 static int backoff_times = 0;
1809 static int backoff_count = 0;
1810
1811 /* process target state changes */
1812 static int handle_target(void *priv)
1813 {
1814         Jim_Interp *interp = (Jim_Interp *)priv;
1815         int retval = ERROR_OK;
1816
1817         if (!is_jtag_poll_safe())
1818         {
1819                 /* polling is disabled currently */
1820                 return ERROR_OK;
1821         }
1822
1823         /* we do not want to recurse here... */
1824         static int recursive = 0;
1825         if (! recursive)
1826         {
1827                 recursive = 1;
1828                 sense_handler();
1829                 /* danger! running these procedures can trigger srst assertions and power dropouts.
1830                  * We need to avoid an infinite loop/recursion here and we do that by
1831                  * clearing the flags after running these events.
1832                  */
1833                 int did_something = 0;
1834                 if (runSrstAsserted)
1835                 {
1836                         LOG_INFO("srst asserted detected, running srst_asserted proc.");
1837                         Jim_Eval(interp, "srst_asserted");
1838                         did_something = 1;
1839                 }
1840                 if (runSrstDeasserted)
1841                 {
1842                         Jim_Eval(interp, "srst_deasserted");
1843                         did_something = 1;
1844                 }
1845                 if (runPowerDropout)
1846                 {
1847                         LOG_INFO("Power dropout detected, running power_dropout proc.");
1848                         Jim_Eval(interp, "power_dropout");
1849                         did_something = 1;
1850                 }
1851                 if (runPowerRestore)
1852                 {
1853                         Jim_Eval(interp, "power_restore");
1854                         did_something = 1;
1855                 }
1856
1857                 if (did_something)
1858                 {
1859                         /* clear detect flags */
1860                         sense_handler();
1861                 }
1862
1863                 /* clear action flags */
1864
1865                 runSrstAsserted = 0;
1866                 runSrstDeasserted = 0;
1867                 runPowerRestore = 0;
1868                 runPowerDropout = 0;
1869
1870                 recursive = 0;
1871         }
1872
1873         if (backoff_times > backoff_count)
1874         {
1875                 /* do not poll this time as we failed previously */
1876                 backoff_count++;
1877                 return ERROR_OK;
1878         }
1879         backoff_count = 0;
1880
1881         /* Poll targets for state changes unless that's globally disabled.
1882          * Skip targets that are currently disabled.
1883          */
1884         for (struct target *target = all_targets;
1885                         is_jtag_poll_safe() && target;
1886                         target = target->next)
1887         {
1888                 if (!target->tap->enabled)
1889                         continue;
1890
1891                 /* only poll target if we've got power and srst isn't asserted */
1892                 if (!powerDropout && !srstAsserted)
1893                 {
1894                         /* polling may fail silently until the target has been examined */
1895                         if ((retval = target_poll(target)) != ERROR_OK)
1896                         {
1897                                 /* 100ms polling interval. Increase interval between polling up to 5000ms */
1898                                 if (backoff_times * polling_interval < 5000)
1899                                 {
1900                                         backoff_times *= 2;
1901                                         backoff_times++;
1902                                 }
1903                                 LOG_USER("Polling target failed, GDB will be halted. Polling again in %dms", backoff_times * polling_interval);
1904
1905                                 /* Tell GDB to halt the debugger. This allows the user to
1906                                  * run monitor commands to handle the situation.
1907                                  */
1908                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1909                                 return retval;
1910                         }
1911                         /* Since we succeeded, we reset backoff count */
1912                         if (backoff_times > 0)
1913                         {
1914                                 LOG_USER("Polling succeeded again");
1915                         }
1916                         backoff_times = 0;
1917                 }
1918         }
1919
1920         return retval;
1921 }
1922
1923 COMMAND_HANDLER(handle_reg_command)
1924 {
1925         struct target *target;
1926         struct reg *reg = NULL;
1927         unsigned count = 0;
1928         char *value;
1929
1930         LOG_DEBUG("-");
1931
1932         target = get_current_target(CMD_CTX);
1933
1934         /* list all available registers for the current target */
1935         if (CMD_ARGC == 0)
1936         {
1937                 struct reg_cache *cache = target->reg_cache;
1938
1939                 count = 0;
1940                 while (cache)
1941                 {
1942                         unsigned i;
1943
1944                         command_print(CMD_CTX, "===== %s", cache->name);
1945
1946                         for (i = 0, reg = cache->reg_list;
1947                                         i < cache->num_regs;
1948                                         i++, reg++, count++)
1949                         {
1950                                 /* only print cached values if they are valid */
1951                                 if (reg->valid) {
1952                                         value = buf_to_str(reg->value,
1953                                                         reg->size, 16);
1954                                         command_print(CMD_CTX,
1955                                                         "(%i) %s (/%" PRIu32 "): 0x%s%s",
1956                                                         count, reg->name,
1957                                                         reg->size, value,
1958                                                         reg->dirty
1959                                                                 ? " (dirty)"
1960                                                                 : "");
1961                                         free(value);
1962                                 } else {
1963                                         command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1964                                                           count, reg->name,
1965                                                           reg->size) ;
1966                                 }
1967                         }
1968                         cache = cache->next;
1969                 }
1970
1971                 return ERROR_OK;
1972         }
1973
1974         /* access a single register by its ordinal number */
1975         if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1976         {
1977                 unsigned num;
1978                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1979
1980                 struct reg_cache *cache = target->reg_cache;
1981                 count = 0;
1982                 while (cache)
1983                 {
1984                         unsigned i;
1985                         for (i = 0; i < cache->num_regs; i++)
1986                         {
1987                                 if (count++ == num)
1988                                 {
1989                                         reg = &cache->reg_list[i];
1990                                         break;
1991                                 }
1992                         }
1993                         if (reg)
1994                                 break;
1995                         cache = cache->next;
1996                 }
1997
1998                 if (!reg)
1999                 {
2000                         command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2001                         return ERROR_OK;
2002                 }
2003         } else /* access a single register by its name */
2004         {
2005                 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
2006
2007                 if (!reg)
2008                 {
2009                         command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
2010                         return ERROR_OK;
2011                 }
2012         }
2013
2014         /* display a register */
2015         if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
2016         {
2017                 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
2018                         reg->valid = 0;
2019
2020                 if (reg->valid == 0)
2021                 {
2022                         reg->type->get(reg);
2023                 }
2024                 value = buf_to_str(reg->value, reg->size, 16);
2025                 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2026                 free(value);
2027                 return ERROR_OK;
2028         }
2029
2030         /* set register value */
2031         if (CMD_ARGC == 2)
2032         {
2033                 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
2034                 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
2035
2036                 reg->type->set(reg, buf);
2037
2038                 value = buf_to_str(reg->value, reg->size, 16);
2039                 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2040                 free(value);
2041
2042                 free(buf);
2043
2044                 return ERROR_OK;
2045         }
2046
2047         command_print(CMD_CTX, "usage: reg <#|name> [value]");
2048
2049         return ERROR_OK;
2050 }
2051
2052 COMMAND_HANDLER(handle_poll_command)
2053 {
2054         int retval = ERROR_OK;
2055         struct target *target = get_current_target(CMD_CTX);
2056
2057         if (CMD_ARGC == 0)
2058         {
2059                 command_print(CMD_CTX, "background polling: %s",
2060                                 jtag_poll_get_enabled() ? "on" : "off");
2061                 command_print(CMD_CTX, "TAP: %s (%s)",
2062                                 target->tap->dotted_name,
2063                                 target->tap->enabled ? "enabled" : "disabled");
2064                 if (!target->tap->enabled)
2065                         return ERROR_OK;
2066                 if ((retval = target_poll(target)) != ERROR_OK)
2067                         return retval;
2068                 if ((retval = target_arch_state(target)) != ERROR_OK)
2069                         return retval;
2070         }
2071         else if (CMD_ARGC == 1)
2072         {
2073                 bool enable;
2074                 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
2075                 jtag_poll_set_enabled(enable);
2076         }
2077         else
2078         {
2079                 return ERROR_COMMAND_SYNTAX_ERROR;
2080         }
2081
2082         return retval;
2083 }
2084
2085 COMMAND_HANDLER(handle_wait_halt_command)
2086 {
2087         if (CMD_ARGC > 1)
2088                 return ERROR_COMMAND_SYNTAX_ERROR;
2089
2090         unsigned ms = 5000;
2091         if (1 == CMD_ARGC)
2092         {
2093                 int retval = parse_uint(CMD_ARGV[0], &ms);
2094                 if (ERROR_OK != retval)
2095                 {
2096                         command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
2097                         return ERROR_COMMAND_SYNTAX_ERROR;
2098                 }
2099                 // convert seconds (given) to milliseconds (needed)
2100                 ms *= 1000;
2101         }
2102
2103         struct target *target = get_current_target(CMD_CTX);
2104         return target_wait_state(target, TARGET_HALTED, ms);
2105 }
2106
2107 /* wait for target state to change. The trick here is to have a low
2108  * latency for short waits and not to suck up all the CPU time
2109  * on longer waits.
2110  *
2111  * After 500ms, keep_alive() is invoked
2112  */
2113 int target_wait_state(struct target *target, enum target_state state, int ms)
2114 {
2115         int retval;
2116         long long then = 0, cur;
2117         int once = 1;
2118
2119         for (;;)
2120         {
2121                 if ((retval = target_poll(target)) != ERROR_OK)
2122                         return retval;
2123                 if (target->state == state)
2124                 {
2125                         break;
2126                 }
2127                 cur = timeval_ms();
2128                 if (once)
2129                 {
2130                         once = 0;
2131                         then = timeval_ms();
2132                         LOG_DEBUG("waiting for target %s...",
2133                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2134                 }
2135
2136                 if (cur-then > 500)
2137                 {
2138                         keep_alive();
2139                 }
2140
2141                 if ((cur-then) > ms)
2142                 {
2143                         LOG_ERROR("timed out while waiting for target %s",
2144                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2145                         return ERROR_FAIL;
2146                 }
2147         }
2148
2149         return ERROR_OK;
2150 }
2151
2152 COMMAND_HANDLER(handle_halt_command)
2153 {
2154         LOG_DEBUG("-");
2155
2156         struct target *target = get_current_target(CMD_CTX);
2157         int retval = target_halt(target);
2158         if (ERROR_OK != retval)
2159                 return retval;
2160
2161         if (CMD_ARGC == 1)
2162         {
2163                 unsigned wait_local;
2164                 retval = parse_uint(CMD_ARGV[0], &wait_local);
2165                 if (ERROR_OK != retval)
2166                         return ERROR_COMMAND_SYNTAX_ERROR;
2167                 if (!wait_local)
2168                         return ERROR_OK;
2169         }
2170
2171         return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2172 }
2173
2174 COMMAND_HANDLER(handle_soft_reset_halt_command)
2175 {
2176         struct target *target = get_current_target(CMD_CTX);
2177
2178         LOG_USER("requesting target halt and executing a soft reset");
2179
2180         target->type->soft_reset_halt(target);
2181
2182         return ERROR_OK;
2183 }
2184
2185 COMMAND_HANDLER(handle_reset_command)
2186 {
2187         if (CMD_ARGC > 1)
2188                 return ERROR_COMMAND_SYNTAX_ERROR;
2189
2190         enum target_reset_mode reset_mode = RESET_RUN;
2191         if (CMD_ARGC == 1)
2192         {
2193                 const Jim_Nvp *n;
2194                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2195                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2196                         return ERROR_COMMAND_SYNTAX_ERROR;
2197                 }
2198                 reset_mode = n->value;
2199         }
2200
2201         /* reset *all* targets */
2202         return target_process_reset(CMD_CTX, reset_mode);
2203 }
2204
2205
2206 COMMAND_HANDLER(handle_resume_command)
2207 {
2208         int current = 1;
2209         if (CMD_ARGC > 1)
2210                 return ERROR_COMMAND_SYNTAX_ERROR;
2211
2212         struct target *target = get_current_target(CMD_CTX);
2213         target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2214
2215         /* with no CMD_ARGV, resume from current pc, addr = 0,
2216          * with one arguments, addr = CMD_ARGV[0],
2217          * handle breakpoints, not debugging */
2218         uint32_t addr = 0;
2219         if (CMD_ARGC == 1)
2220         {
2221                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2222                 current = 0;
2223         }
2224
2225         return target_resume(target, current, addr, 1, 0);
2226 }
2227
2228 COMMAND_HANDLER(handle_step_command)
2229 {
2230         if (CMD_ARGC > 1)
2231                 return ERROR_COMMAND_SYNTAX_ERROR;
2232
2233         LOG_DEBUG("-");
2234
2235         /* with no CMD_ARGV, step from current pc, addr = 0,
2236          * with one argument addr = CMD_ARGV[0],
2237          * handle breakpoints, debugging */
2238         uint32_t addr = 0;
2239         int current_pc = 1;
2240         if (CMD_ARGC == 1)
2241         {
2242                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2243                 current_pc = 0;
2244         }
2245
2246         struct target *target = get_current_target(CMD_CTX);
2247
2248         return target->type->step(target, current_pc, addr, 1);
2249 }
2250
2251 static void handle_md_output(struct command_context *cmd_ctx,
2252                 struct target *target, uint32_t address, unsigned size,
2253                 unsigned count, const uint8_t *buffer)
2254 {
2255         const unsigned line_bytecnt = 32;
2256         unsigned line_modulo = line_bytecnt / size;
2257
2258         char output[line_bytecnt * 4 + 1];
2259         unsigned output_len = 0;
2260
2261         const char *value_fmt;
2262         switch (size) {
2263         case 4: value_fmt = "%8.8x "; break;
2264         case 2: value_fmt = "%4.4x "; break;
2265         case 1: value_fmt = "%2.2x "; break;
2266         default:
2267                 /* "can't happen", caller checked */
2268                 LOG_ERROR("invalid memory read size: %u", size);
2269                 return;
2270         }
2271
2272         for (unsigned i = 0; i < count; i++)
2273         {
2274                 if (i % line_modulo == 0)
2275                 {
2276                         output_len += snprintf(output + output_len,
2277                                         sizeof(output) - output_len,
2278                                         "0x%8.8x: ",
2279                                         (unsigned)(address + (i*size)));
2280                 }
2281
2282                 uint32_t value = 0;
2283                 const uint8_t *value_ptr = buffer + i * size;
2284                 switch (size) {
2285                 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2286                 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2287                 case 1: value = *value_ptr;
2288                 }
2289                 output_len += snprintf(output + output_len,
2290                                 sizeof(output) - output_len,
2291                                 value_fmt, value);
2292
2293                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2294                 {
2295                         command_print(cmd_ctx, "%s", output);
2296                         output_len = 0;
2297                 }
2298         }
2299 }
2300
2301 COMMAND_HANDLER(handle_md_command)
2302 {
2303         if (CMD_ARGC < 1)
2304                 return ERROR_COMMAND_SYNTAX_ERROR;
2305
2306         unsigned size = 0;
2307         switch (CMD_NAME[2]) {
2308         case 'w': size = 4; break;
2309         case 'h': size = 2; break;
2310         case 'b': size = 1; break;
2311         default: return ERROR_COMMAND_SYNTAX_ERROR;
2312         }
2313
2314         bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2315         int (*fn)(struct target *target,
2316                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2317         if (physical)
2318         {
2319                 CMD_ARGC--;
2320                 CMD_ARGV++;
2321                 fn=target_read_phys_memory;
2322         } else
2323         {
2324                 fn=target_read_memory;
2325         }
2326         if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2327         {
2328                 return ERROR_COMMAND_SYNTAX_ERROR;
2329         }
2330
2331         uint32_t address;
2332         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2333
2334         unsigned count = 1;
2335         if (CMD_ARGC == 2)
2336                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2337
2338         uint8_t *buffer = calloc(count, size);
2339
2340         struct target *target = get_current_target(CMD_CTX);
2341         int retval = fn(target, address, size, count, buffer);
2342         if (ERROR_OK == retval)
2343                 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2344
2345         free(buffer);
2346
2347         return retval;
2348 }
2349
2350 typedef int (*target_write_fn)(struct target *target,
2351                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2352
2353 static int target_write_memory_fast(struct target *target,
2354                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
2355 {
2356         return target_write_buffer(target, address, size * count, buffer);
2357 }
2358
2359 static int target_fill_mem(struct target *target,
2360                 uint32_t address,
2361                 target_write_fn fn,
2362                 unsigned data_size,
2363                 /* value */
2364                 uint32_t b,
2365                 /* count */
2366                 unsigned c)
2367 {
2368         /* We have to write in reasonably large chunks to be able
2369          * to fill large memory areas with any sane speed */
2370         const unsigned chunk_size = 16384;
2371         uint8_t *target_buf = malloc(chunk_size * data_size);
2372         if (target_buf == NULL)
2373         {
2374                 LOG_ERROR("Out of memory");
2375                 return ERROR_FAIL;
2376         }
2377
2378         for (unsigned i = 0; i < chunk_size; i ++)
2379         {
2380                 switch (data_size)
2381                 {
2382                 case 4:
2383                         target_buffer_set_u32(target, target_buf + i*data_size, b);
2384                         break;
2385                 case 2:
2386                         target_buffer_set_u16(target, target_buf + i*data_size, b);
2387                         break;
2388                 case 1:
2389                         target_buffer_set_u8(target, target_buf + i*data_size, b);
2390                         break;
2391                 default:
2392                         exit(-1);
2393                 }
2394         }
2395
2396         int retval = ERROR_OK;
2397
2398         for (unsigned x = 0; x < c; x += chunk_size)
2399         {
2400                 unsigned current;
2401                 current = c - x;
2402                 if (current > chunk_size)
2403                 {
2404                         current = chunk_size;
2405                 }
2406                 retval = fn(target, address + x * data_size, data_size, current, target_buf);
2407                 if (retval != ERROR_OK)
2408                 {
2409                         break;
2410                 }
2411                 /* avoid GDB timeouts */
2412                 keep_alive();
2413         }
2414         free(target_buf);
2415
2416         return retval;
2417 }
2418
2419
2420 COMMAND_HANDLER(handle_mw_command)
2421 {
2422         if (CMD_ARGC < 2)
2423         {
2424                 return ERROR_COMMAND_SYNTAX_ERROR;
2425         }
2426         bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2427         target_write_fn fn;
2428         if (physical)
2429         {
2430                 CMD_ARGC--;
2431                 CMD_ARGV++;
2432                 fn=target_write_phys_memory;
2433         } else
2434         {
2435                 fn = target_write_memory_fast;
2436         }
2437         if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2438                 return ERROR_COMMAND_SYNTAX_ERROR;
2439
2440         uint32_t address;
2441         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2442
2443         uint32_t value;
2444         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2445
2446         unsigned count = 1;
2447         if (CMD_ARGC == 3)
2448                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2449
2450         struct target *target = get_current_target(CMD_CTX);
2451         unsigned wordsize;
2452         switch (CMD_NAME[2])
2453         {
2454                 case 'w':
2455                         wordsize = 4;
2456                         break;
2457                 case 'h':
2458                         wordsize = 2;
2459                         break;
2460                 case 'b':
2461                         wordsize = 1;
2462                         break;
2463                 default:
2464                         return ERROR_COMMAND_SYNTAX_ERROR;
2465         }
2466
2467         return target_fill_mem(target, address, fn, wordsize, value, count);
2468 }
2469
2470 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2471                 uint32_t *min_address, uint32_t *max_address)
2472 {
2473         if (CMD_ARGC < 1 || CMD_ARGC > 5)
2474                 return ERROR_COMMAND_SYNTAX_ERROR;
2475
2476         /* a base address isn't always necessary,
2477          * default to 0x0 (i.e. don't relocate) */
2478         if (CMD_ARGC >= 2)
2479         {
2480                 uint32_t addr;
2481                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2482                 image->base_address = addr;
2483                 image->base_address_set = 1;
2484         }
2485         else
2486                 image->base_address_set = 0;
2487
2488         image->start_address_set = 0;
2489
2490         if (CMD_ARGC >= 4)
2491         {
2492                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2493         }
2494         if (CMD_ARGC == 5)
2495         {
2496                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2497                 // use size (given) to find max (required)
2498                 *max_address += *min_address;
2499         }
2500
2501         if (*min_address > *max_address)
2502                 return ERROR_COMMAND_SYNTAX_ERROR;
2503
2504         return ERROR_OK;
2505 }
2506
2507 COMMAND_HANDLER(handle_load_image_command)
2508 {
2509         uint8_t *buffer;
2510         size_t buf_cnt;
2511         uint32_t image_size;
2512         uint32_t min_address = 0;
2513         uint32_t max_address = 0xffffffff;
2514         int i;
2515         struct image image;
2516
2517         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2518                         &image, &min_address, &max_address);
2519         if (ERROR_OK != retval)
2520                 return retval;
2521
2522         struct target *target = get_current_target(CMD_CTX);
2523
2524         struct duration bench;
2525         duration_start(&bench);
2526
2527         if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2528         {
2529                 return ERROR_OK;
2530         }
2531
2532         image_size = 0x0;
2533         retval = ERROR_OK;
2534         for (i = 0; i < image.num_sections; i++)
2535         {
2536                 buffer = malloc(image.sections[i].size);
2537                 if (buffer == NULL)
2538                 {
2539                         command_print(CMD_CTX,
2540                                                   "error allocating buffer for section (%d bytes)",
2541                                                   (int)(image.sections[i].size));
2542                         break;
2543                 }
2544
2545                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2546                 {
2547                         free(buffer);
2548                         break;
2549                 }
2550
2551                 uint32_t offset = 0;
2552                 uint32_t length = buf_cnt;
2553
2554                 /* DANGER!!! beware of unsigned comparision here!!! */
2555
2556                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2557                                 (image.sections[i].base_address < max_address))
2558                 {
2559                         if (image.sections[i].base_address < min_address)
2560                         {
2561                                 /* clip addresses below */
2562                                 offset += min_address-image.sections[i].base_address;
2563                                 length -= offset;
2564                         }
2565
2566                         if (image.sections[i].base_address + buf_cnt > max_address)
2567                         {
2568                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2569                         }
2570
2571                         if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2572                         {
2573                                 free(buffer);
2574                                 break;
2575                         }
2576                         image_size += length;
2577                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2578                                                   (unsigned int)length,
2579                                                   image.sections[i].base_address + offset);
2580                 }
2581
2582                 free(buffer);
2583         }
2584
2585         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2586         {
2587                 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2588                                 "in %fs (%0.3f KiB/s)", image_size,
2589                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2590         }
2591
2592         image_close(&image);
2593
2594         return retval;
2595
2596 }
2597
2598 COMMAND_HANDLER(handle_dump_image_command)
2599 {
2600         struct fileio fileio;
2601
2602         uint8_t buffer[560];
2603         int retvaltemp;
2604
2605
2606         struct target *target = get_current_target(CMD_CTX);
2607
2608         if (CMD_ARGC != 3)
2609         {
2610                 command_print(CMD_CTX, "usage: dump_image <filename> <address> <size>");
2611                 return ERROR_OK;
2612         }
2613
2614         uint32_t address;
2615         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2616         uint32_t size;
2617         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2618
2619         if (fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2620         {
2621                 return ERROR_OK;
2622         }
2623
2624         struct duration bench;
2625         duration_start(&bench);
2626
2627         int retval = ERROR_OK;
2628         while (size > 0)
2629         {
2630                 size_t size_written;
2631                 uint32_t this_run_size = (size > 560) ? 560 : size;
2632                 retval = target_read_buffer(target, address, this_run_size, buffer);
2633                 if (retval != ERROR_OK)
2634                 {
2635                         break;
2636                 }
2637
2638                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2639                 if (retval != ERROR_OK)
2640                 {
2641                         break;
2642                 }
2643
2644                 size -= this_run_size;
2645                 address += this_run_size;
2646         }
2647
2648         if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2649                 return retvaltemp;
2650
2651         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2652         {
2653                 command_print(CMD_CTX,
2654                                 "dumped %ld bytes in %fs (%0.3f KiB/s)", (long)fileio.size,
2655                                 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2656         }
2657
2658         return retval;
2659 }
2660
2661 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2662 {
2663         uint8_t *buffer;
2664         size_t buf_cnt;
2665         uint32_t image_size;
2666         int i;
2667         int retval;
2668         uint32_t checksum = 0;
2669         uint32_t mem_checksum = 0;
2670
2671         struct image image;
2672
2673         struct target *target = get_current_target(CMD_CTX);
2674
2675         if (CMD_ARGC < 1)
2676         {
2677                 return ERROR_COMMAND_SYNTAX_ERROR;
2678         }
2679
2680         if (!target)
2681         {
2682                 LOG_ERROR("no target selected");
2683                 return ERROR_FAIL;
2684         }
2685
2686         struct duration bench;
2687         duration_start(&bench);
2688
2689         if (CMD_ARGC >= 2)
2690         {
2691                 uint32_t addr;
2692                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2693                 image.base_address = addr;
2694                 image.base_address_set = 1;
2695         }
2696         else
2697         {
2698                 image.base_address_set = 0;
2699                 image.base_address = 0x0;
2700         }
2701
2702         image.start_address_set = 0;
2703
2704         if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2705         {
2706                 return retval;
2707         }
2708
2709         image_size = 0x0;
2710         int diffs = 0;
2711         retval = ERROR_OK;
2712         for (i = 0; i < image.num_sections; i++)
2713         {
2714                 buffer = malloc(image.sections[i].size);
2715                 if (buffer == NULL)
2716                 {
2717                         command_print(CMD_CTX,
2718                                                   "error allocating buffer for section (%d bytes)",
2719                                                   (int)(image.sections[i].size));
2720                         break;
2721                 }
2722                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2723                 {
2724                         free(buffer);
2725                         break;
2726                 }
2727
2728                 if (verify)
2729                 {
2730                         /* calculate checksum of image */
2731                         retval = image_calculate_checksum(buffer, buf_cnt, &checksum);
2732                         if (retval != ERROR_OK)
2733                         {
2734                                 free(buffer);
2735                                 break;
2736                         }
2737
2738                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2739                         if (retval != ERROR_OK)
2740                         {
2741                                 free(buffer);
2742                                 break;
2743                         }
2744
2745                         if (checksum != mem_checksum)
2746                         {
2747                                 /* failed crc checksum, fall back to a binary compare */
2748                                 uint8_t *data;
2749
2750                                 if (diffs == 0)
2751                                 {
2752                                         LOG_ERROR("checksum mismatch - attempting binary compare");
2753                                 }
2754
2755                                 data = (uint8_t*)malloc(buf_cnt);
2756
2757                                 /* Can we use 32bit word accesses? */
2758                                 int size = 1;
2759                                 int count = buf_cnt;
2760                                 if ((count % 4) == 0)
2761                                 {
2762                                         size *= 4;
2763                                         count /= 4;
2764                                 }
2765                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2766                                 if (retval == ERROR_OK)
2767                                 {
2768                                         uint32_t t;
2769                                         for (t = 0; t < buf_cnt; t++)
2770                                         {
2771                                                 if (data[t] != buffer[t])
2772                                                 {
2773                                                         command_print(CMD_CTX,
2774                                                                                   "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
2775                                                                                   diffs,
2776                                                                                   (unsigned)(t + image.sections[i].base_address),
2777                                                                                   data[t],
2778                                                                                   buffer[t]);
2779                                                         if (diffs++ >= 127)
2780                                                         {
2781                                                                 command_print(CMD_CTX, "More than 128 errors, the rest are not printed.");
2782                                                                 free(data);
2783                                                                 free(buffer);
2784                                                                 goto done;
2785                                                         }
2786                                                 }
2787                                                 keep_alive();
2788                                         }
2789                                 }
2790                                 free(data);
2791                         }
2792                 } else
2793                 {
2794                         command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2795                                                   image.sections[i].base_address,
2796                                                   buf_cnt);
2797                 }
2798
2799                 free(buffer);
2800                 image_size += buf_cnt;
2801         }
2802         if (diffs > 0)
2803         {
2804                 command_print(CMD_CTX, "No more differences found.");
2805         }
2806 done:
2807         if (diffs > 0)
2808         {
2809                 retval = ERROR_FAIL;
2810         }
2811         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2812         {
2813                 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2814                                 "in %fs (%0.3f KiB/s)", image_size,
2815                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2816         }
2817
2818         image_close(&image);
2819
2820         return retval;
2821 }
2822
2823 COMMAND_HANDLER(handle_verify_image_command)
2824 {
2825         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2826 }
2827
2828 COMMAND_HANDLER(handle_test_image_command)
2829 {
2830         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2831 }
2832
2833 static int handle_bp_command_list(struct command_context *cmd_ctx)
2834 {
2835         struct target *target = get_current_target(cmd_ctx);
2836         struct breakpoint *breakpoint = target->breakpoints;
2837         while (breakpoint)
2838         {
2839                 if (breakpoint->type == BKPT_SOFT)
2840                 {
2841                         char* buf = buf_to_str(breakpoint->orig_instr,
2842                                         breakpoint->length, 16);
2843                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2844                                         breakpoint->address,
2845                                         breakpoint->length,
2846                                         breakpoint->set, buf);
2847                         free(buf);
2848                 }
2849                 else
2850                 {
2851                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2852                                                   breakpoint->address,
2853                                                   breakpoint->length, breakpoint->set);
2854                 }
2855
2856                 breakpoint = breakpoint->next;
2857         }
2858         return ERROR_OK;
2859 }
2860
2861 static int handle_bp_command_set(struct command_context *cmd_ctx,
2862                 uint32_t addr, uint32_t length, int hw)
2863 {
2864         struct target *target = get_current_target(cmd_ctx);
2865         int retval = breakpoint_add(target, addr, length, hw);
2866         if (ERROR_OK == retval)
2867                 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2868         else
2869                 LOG_ERROR("Failure setting breakpoint");
2870         return retval;
2871 }
2872
2873 COMMAND_HANDLER(handle_bp_command)
2874 {
2875         if (CMD_ARGC == 0)
2876                 return handle_bp_command_list(CMD_CTX);
2877
2878         if (CMD_ARGC < 2 || CMD_ARGC > 3)
2879         {
2880                 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2881                 return ERROR_COMMAND_SYNTAX_ERROR;
2882         }
2883
2884         uint32_t addr;
2885         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2886         uint32_t length;
2887         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2888
2889         int hw = BKPT_SOFT;
2890         if (CMD_ARGC == 3)
2891         {
2892                 if (strcmp(CMD_ARGV[2], "hw") == 0)
2893                         hw = BKPT_HARD;
2894                 else
2895                         return ERROR_COMMAND_SYNTAX_ERROR;
2896         }
2897
2898         return handle_bp_command_set(CMD_CTX, addr, length, hw);
2899 }
2900
2901 COMMAND_HANDLER(handle_rbp_command)
2902 {
2903         if (CMD_ARGC != 1)
2904                 return ERROR_COMMAND_SYNTAX_ERROR;
2905
2906         uint32_t addr;
2907         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2908
2909         struct target *target = get_current_target(CMD_CTX);
2910         breakpoint_remove(target, addr);
2911
2912         return ERROR_OK;
2913 }
2914
2915 COMMAND_HANDLER(handle_wp_command)
2916 {
2917         struct target *target = get_current_target(CMD_CTX);
2918
2919         if (CMD_ARGC == 0)
2920         {
2921                 struct watchpoint *watchpoint = target->watchpoints;
2922
2923                 while (watchpoint)
2924                 {
2925                         command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2926                                         ", len: 0x%8.8" PRIx32
2927                                         ", r/w/a: %i, value: 0x%8.8" PRIx32
2928                                         ", mask: 0x%8.8" PRIx32,
2929                                         watchpoint->address,
2930                                         watchpoint->length,
2931                                         (int)watchpoint->rw,
2932                                         watchpoint->value,
2933                                         watchpoint->mask);
2934                         watchpoint = watchpoint->next;
2935                 }
2936                 return ERROR_OK;
2937         }
2938
2939         enum watchpoint_rw type = WPT_ACCESS;
2940         uint32_t addr = 0;
2941         uint32_t length = 0;
2942         uint32_t data_value = 0x0;
2943         uint32_t data_mask = 0xffffffff;
2944
2945         switch (CMD_ARGC)
2946         {
2947         case 5:
2948                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2949                 // fall through
2950         case 4:
2951                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2952                 // fall through
2953         case 3:
2954                 switch (CMD_ARGV[2][0])
2955                 {
2956                 case 'r':
2957                         type = WPT_READ;
2958                         break;
2959                 case 'w':
2960                         type = WPT_WRITE;
2961                         break;
2962                 case 'a':
2963                         type = WPT_ACCESS;
2964                         break;
2965                 default:
2966                         LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2967                         return ERROR_COMMAND_SYNTAX_ERROR;
2968                 }
2969                 // fall through
2970         case 2:
2971                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2972                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2973                 break;
2974
2975         default:
2976                 command_print(CMD_CTX, "usage: wp [address length "
2977                                 "[(r|w|a) [value [mask]]]]");
2978                 return ERROR_COMMAND_SYNTAX_ERROR;
2979         }
2980
2981         int retval = watchpoint_add(target, addr, length, type,
2982                         data_value, data_mask);
2983         if (ERROR_OK != retval)
2984                 LOG_ERROR("Failure setting watchpoints");
2985
2986         return retval;
2987 }
2988
2989 COMMAND_HANDLER(handle_rwp_command)
2990 {
2991         if (CMD_ARGC != 1)
2992                 return ERROR_COMMAND_SYNTAX_ERROR;
2993
2994         uint32_t addr;
2995         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2996
2997         struct target *target = get_current_target(CMD_CTX);
2998         watchpoint_remove(target, addr);
2999
3000         return ERROR_OK;
3001 }
3002
3003
3004 /**
3005  * Translate a virtual address to a physical address.
3006  *
3007  * The low-level target implementation must have logged a detailed error
3008  * which is forwarded to telnet/GDB session.
3009  */
3010 COMMAND_HANDLER(handle_virt2phys_command)
3011 {
3012         if (CMD_ARGC != 1)
3013                 return ERROR_COMMAND_SYNTAX_ERROR;
3014
3015         uint32_t va;
3016         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
3017         uint32_t pa;
3018
3019         struct target *target = get_current_target(CMD_CTX);
3020         int retval = target->type->virt2phys(target, va, &pa);
3021         if (retval == ERROR_OK)
3022                 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
3023
3024         return retval;
3025 }
3026
3027 static void writeData(FILE *f, const void *data, size_t len)
3028 {
3029         size_t written = fwrite(data, 1, len, f);
3030         if (written != len)
3031                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3032 }
3033
3034 static void writeLong(FILE *f, int l)
3035 {
3036         int i;
3037         for (i = 0; i < 4; i++)
3038         {
3039                 char c = (l >> (i*8))&0xff;
3040                 writeData(f, &c, 1);
3041         }
3042
3043 }
3044
3045 static void writeString(FILE *f, char *s)
3046 {
3047         writeData(f, s, strlen(s));
3048 }
3049
3050 /* Dump a gmon.out histogram file. */
3051 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
3052 {
3053         uint32_t i;
3054         FILE *f = fopen(filename, "w");
3055         if (f == NULL)
3056                 return;
3057         writeString(f, "gmon");
3058         writeLong(f, 0x00000001); /* Version */
3059         writeLong(f, 0); /* padding */
3060         writeLong(f, 0); /* padding */
3061         writeLong(f, 0); /* padding */
3062
3063         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
3064         writeData(f, &zero, 1);
3065
3066         /* figure out bucket size */
3067         uint32_t min = samples[0];
3068         uint32_t max = samples[0];
3069         for (i = 0; i < sampleNum; i++)
3070         {
3071                 if (min > samples[i])
3072                 {
3073                         min = samples[i];
3074                 }
3075                 if (max < samples[i])
3076                 {
3077                         max = samples[i];
3078                 }
3079         }
3080
3081         int addressSpace = (max-min + 1);
3082
3083         static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
3084         uint32_t length = addressSpace;
3085         if (length > maxBuckets)
3086         {
3087                 length = maxBuckets;
3088         }
3089         int *buckets = malloc(sizeof(int)*length);
3090         if (buckets == NULL)
3091         {
3092                 fclose(f);
3093                 return;
3094         }
3095         memset(buckets, 0, sizeof(int)*length);
3096         for (i = 0; i < sampleNum;i++)
3097         {
3098                 uint32_t address = samples[i];
3099                 long long a = address-min;
3100                 long long b = length-1;
3101                 long long c = addressSpace-1;
3102                 int index_t = (a*b)/c; /* danger!!!! int32 overflows */
3103                 buckets[index_t]++;
3104         }
3105
3106         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3107         writeLong(f, min);                      /* low_pc */
3108         writeLong(f, max);                      /* high_pc */
3109         writeLong(f, length);           /* # of samples */
3110         writeLong(f, 64000000);         /* 64MHz */
3111         writeString(f, "seconds");
3112         for (i = 0; i < (15-strlen("seconds")); i++)
3113                 writeData(f, &zero, 1);
3114         writeString(f, "s");
3115
3116         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3117
3118         char *data = malloc(2*length);
3119         if (data != NULL)
3120         {
3121                 for (i = 0; i < length;i++)
3122                 {
3123                         int val;
3124                         val = buckets[i];
3125                         if (val > 65535)
3126                         {
3127                                 val = 65535;
3128                         }
3129                         data[i*2]=val&0xff;
3130                         data[i*2 + 1]=(val >> 8)&0xff;
3131                 }
3132                 free(buckets);
3133                 writeData(f, data, length * 2);
3134                 free(data);
3135         } else
3136         {
3137                 free(buckets);
3138         }
3139
3140         fclose(f);
3141 }
3142
3143 /* profiling samples the CPU PC as quickly as OpenOCD is able,
3144  * which will be used as a random sampling of PC */
3145 COMMAND_HANDLER(handle_profile_command)
3146 {
3147         struct target *target = get_current_target(CMD_CTX);
3148         struct timeval timeout, now;
3149
3150         gettimeofday(&timeout, NULL);
3151         if (CMD_ARGC != 2)
3152         {
3153                 return ERROR_COMMAND_SYNTAX_ERROR;
3154         }
3155         unsigned offset;
3156         COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
3157
3158         timeval_add_time(&timeout, offset, 0);
3159
3160         /**
3161          * @todo: Some cores let us sample the PC without the
3162          * annoying halt/resume step; for example, ARMv7 PCSR.
3163          * Provide a way to use that more efficient mechanism.
3164          */
3165
3166         command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
3167
3168         static const int maxSample = 10000;
3169         uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3170         if (samples == NULL)
3171                 return ERROR_OK;
3172
3173         int numSamples = 0;
3174         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3175         struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
3176
3177         for (;;)
3178         {
3179                 int retval;
3180                 target_poll(target);
3181                 if (target->state == TARGET_HALTED)
3182                 {
3183                         uint32_t t=*((uint32_t *)reg->value);
3184                         samples[numSamples++]=t;
3185                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3186                         target_poll(target);
3187                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3188                 } else if (target->state == TARGET_RUNNING)
3189                 {
3190                         /* We want to quickly sample the PC. */
3191                         if ((retval = target_halt(target)) != ERROR_OK)
3192                         {
3193                                 free(samples);
3194                                 return retval;
3195                         }
3196                 } else
3197                 {
3198                         command_print(CMD_CTX, "Target not halted or running");
3199                         retval = ERROR_OK;
3200                         break;
3201                 }
3202                 if (retval != ERROR_OK)
3203                 {
3204                         break;
3205                 }
3206
3207                 gettimeofday(&now, NULL);
3208                 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3209                 {
3210                         command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
3211                         if ((retval = target_poll(target)) != ERROR_OK)
3212                         {
3213                                 free(samples);
3214                                 return retval;
3215                         }
3216                         if (target->state == TARGET_HALTED)
3217                         {
3218                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3219                         }
3220                         if ((retval = target_poll(target)) != ERROR_OK)
3221                         {
3222                                 free(samples);
3223                                 return retval;
3224                         }
3225                         writeGmon(samples, numSamples, CMD_ARGV[1]);
3226                         command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
3227                         break;
3228                 }
3229         }
3230         free(samples);
3231
3232         return ERROR_OK;
3233 }
3234
3235 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3236 {
3237         char *namebuf;
3238         Jim_Obj *nameObjPtr, *valObjPtr;
3239         int result;
3240
3241         namebuf = alloc_printf("%s(%d)", varname, idx);
3242         if (!namebuf)
3243                 return JIM_ERR;
3244
3245         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3246         valObjPtr = Jim_NewIntObj(interp, val);
3247         if (!nameObjPtr || !valObjPtr)
3248         {
3249                 free(namebuf);
3250                 return JIM_ERR;
3251         }
3252
3253         Jim_IncrRefCount(nameObjPtr);
3254         Jim_IncrRefCount(valObjPtr);
3255         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3256         Jim_DecrRefCount(interp, nameObjPtr);
3257         Jim_DecrRefCount(interp, valObjPtr);
3258         free(namebuf);
3259         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3260         return result;
3261 }
3262
3263 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3264 {
3265         struct command_context *context;
3266         struct target *target;
3267
3268         context = current_command_context(interp);
3269         assert (context != NULL);
3270
3271         target = get_current_target(context);
3272         if (target == NULL)
3273         {
3274                 LOG_ERROR("mem2array: no current target");
3275                 return JIM_ERR;
3276         }
3277
3278         return  target_mem2array(interp, target, argc-1, argv + 1);
3279 }
3280
3281 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3282 {
3283         long l;
3284         uint32_t width;
3285         int len;
3286         uint32_t addr;
3287         uint32_t count;
3288         uint32_t v;
3289         const char *varname;
3290         int  n, e, retval;
3291         uint32_t i;
3292
3293         /* argv[1] = name of array to receive the data
3294          * argv[2] = desired width
3295          * argv[3] = memory address
3296          * argv[4] = count of times to read
3297          */
3298         if (argc != 4) {
3299                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3300                 return JIM_ERR;
3301         }
3302         varname = Jim_GetString(argv[0], &len);
3303         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3304
3305         e = Jim_GetLong(interp, argv[1], &l);
3306         width = l;
3307         if (e != JIM_OK) {
3308                 return e;
3309         }
3310
3311         e = Jim_GetLong(interp, argv[2], &l);
3312         addr = l;
3313         if (e != JIM_OK) {
3314                 return e;
3315         }
3316         e = Jim_GetLong(interp, argv[3], &l);
3317         len = l;
3318         if (e != JIM_OK) {
3319                 return e;
3320         }
3321         switch (width) {
3322                 case 8:
3323                         width = 1;
3324                         break;
3325                 case 16:
3326                         width = 2;
3327                         break;
3328                 case 32:
3329                         width = 4;
3330                         break;
3331                 default:
3332                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3333                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3334                         return JIM_ERR;
3335         }
3336         if (len == 0) {
3337                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3338                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3339                 return JIM_ERR;