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