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