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