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