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