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