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