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