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