gdb_server, rtos: Fine-grained RTOS register access
[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                                 /* Can we use 32bit word accesses? */
3640                                 int size = 1;
3641                                 int count = buf_cnt;
3642                                 if ((count % 4) == 0) {
3643                                         size *= 4;
3644                                         count /= 4;
3645                                 }
3646                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
3647                                 if (retval == ERROR_OK) {
3648                                         uint32_t t;
3649                                         for (t = 0; t < buf_cnt; t++) {
3650                                                 if (data[t] != buffer[t]) {
3651                                                         command_print(CMD,
3652                                                                                   "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
3653                                                                                   diffs,
3654                                                                                   (unsigned)(t + image.sections[i].base_address),
3655                                                                                   data[t],
3656                                                                                   buffer[t]);
3657                                                         if (diffs++ >= 127) {
3658                                                                 command_print(CMD, "More than 128 errors, the rest are not printed.");
3659                                                                 free(data);
3660                                                                 free(buffer);
3661                                                                 goto done;
3662                                                         }
3663                                                 }
3664                                                 keep_alive();
3665                                         }
3666                                 }
3667                                 free(data);
3668                         }
3669                 } else {
3670                         command_print(CMD, "address " TARGET_ADDR_FMT " length 0x%08zx",
3671                                                   image.sections[i].base_address,
3672                                                   buf_cnt);
3673                 }
3674
3675                 free(buffer);
3676                 image_size += buf_cnt;
3677         }
3678         if (diffs > 0)
3679                 command_print(CMD, "No more differences found.");
3680 done:
3681         if (diffs > 0)
3682                 retval = ERROR_FAIL;
3683         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
3684                 command_print(CMD, "verified %" PRIu32 " bytes "
3685                                 "in %fs (%0.3f KiB/s)", image_size,
3686                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
3687         }
3688
3689         image_close(&image);
3690
3691         return retval;
3692 }
3693
3694 COMMAND_HANDLER(handle_verify_image_checksum_command)
3695 {
3696         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_CHECKSUM_ONLY);
3697 }
3698
3699 COMMAND_HANDLER(handle_verify_image_command)
3700 {
3701         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_VERIFY);
3702 }
3703
3704 COMMAND_HANDLER(handle_test_image_command)
3705 {
3706         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, IMAGE_TEST);
3707 }
3708
3709 static int handle_bp_command_list(struct command_invocation *cmd)
3710 {
3711         struct target *target = get_current_target(cmd->ctx);
3712         struct breakpoint *breakpoint = target->breakpoints;
3713         while (breakpoint) {
3714                 if (breakpoint->type == BKPT_SOFT) {
3715                         char *buf = buf_to_str(breakpoint->orig_instr,
3716                                         breakpoint->length, 16);
3717                         command_print(cmd, "IVA breakpoint: " TARGET_ADDR_FMT ", 0x%x, %i, 0x%s",
3718                                         breakpoint->address,
3719                                         breakpoint->length,
3720                                         breakpoint->set, buf);
3721                         free(buf);
3722                 } else {
3723                         if ((breakpoint->address == 0) && (breakpoint->asid != 0))
3724                                 command_print(cmd, "Context breakpoint: 0x%8.8" PRIx32 ", 0x%x, %i",
3725                                                         breakpoint->asid,
3726                                                         breakpoint->length, breakpoint->set);
3727                         else if ((breakpoint->address != 0) && (breakpoint->asid != 0)) {
3728                                 command_print(cmd, "Hybrid breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3729                                                         breakpoint->address,
3730                                                         breakpoint->length, breakpoint->set);
3731                                 command_print(cmd, "\t|--->linked with ContextID: 0x%8.8" PRIx32,
3732                                                         breakpoint->asid);
3733                         } else
3734                                 command_print(cmd, "Breakpoint(IVA): " TARGET_ADDR_FMT ", 0x%x, %i",
3735                                                         breakpoint->address,
3736                                                         breakpoint->length, breakpoint->set);
3737                 }
3738
3739                 breakpoint = breakpoint->next;
3740         }
3741         return ERROR_OK;
3742 }
3743
3744 static int handle_bp_command_set(struct command_invocation *cmd,
3745                 target_addr_t addr, uint32_t asid, uint32_t length, int hw)
3746 {
3747         struct target *target = get_current_target(cmd->ctx);
3748         int retval;
3749
3750         if (asid == 0) {
3751                 retval = breakpoint_add(target, addr, length, hw);
3752                 /* error is always logged in breakpoint_add(), do not print it again */
3753                 if (ERROR_OK == retval)
3754                         command_print(cmd, "breakpoint set at " TARGET_ADDR_FMT "", addr);
3755
3756         } else if (addr == 0) {
3757                 if (target->type->add_context_breakpoint == NULL) {
3758                         LOG_ERROR("Context breakpoint not available");
3759                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3760                 }
3761                 retval = context_breakpoint_add(target, asid, length, hw);
3762                 /* error is always logged in context_breakpoint_add(), do not print it again */
3763                 if (ERROR_OK == retval)
3764                         command_print(cmd, "Context breakpoint set at 0x%8.8" PRIx32 "", asid);
3765
3766         } else {
3767                 if (target->type->add_hybrid_breakpoint == NULL) {
3768                         LOG_ERROR("Hybrid breakpoint not available");
3769                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
3770                 }
3771                 retval = hybrid_breakpoint_add(target, addr, asid, length, hw);
3772                 /* error is always logged in hybrid_breakpoint_add(), do not print it again */
3773                 if (ERROR_OK == retval)
3774                         command_print(cmd, "Hybrid breakpoint set at 0x%8.8" PRIx32 "", asid);
3775         }
3776         return retval;
3777 }
3778
3779 COMMAND_HANDLER(handle_bp_command)
3780 {
3781         target_addr_t addr;
3782         uint32_t asid;
3783         uint32_t length;
3784         int hw = BKPT_SOFT;
3785
3786         switch (CMD_ARGC) {
3787                 case 0:
3788                         return handle_bp_command_list(CMD);
3789
3790                 case 2:
3791                         asid = 0;
3792                         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3793                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3794                         return handle_bp_command_set(CMD, addr, asid, length, hw);
3795
3796                 case 3:
3797                         if (strcmp(CMD_ARGV[2], "hw") == 0) {
3798                                 hw = BKPT_HARD;
3799                                 COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3800                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3801                                 asid = 0;
3802                                 return handle_bp_command_set(CMD, addr, asid, length, hw);
3803                         } else if (strcmp(CMD_ARGV[2], "hw_ctx") == 0) {
3804                                 hw = BKPT_HARD;
3805                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], asid);
3806                                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3807                                 addr = 0;
3808                                 return handle_bp_command_set(CMD, addr, asid, length, hw);
3809                         }
3810                         /* fallthrough */
3811                 case 4:
3812                         hw = BKPT_HARD;
3813                         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3814                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], asid);
3815                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], length);
3816                         return handle_bp_command_set(CMD, addr, asid, length, hw);
3817
3818                 default:
3819                         return ERROR_COMMAND_SYNTAX_ERROR;
3820         }
3821 }
3822
3823 COMMAND_HANDLER(handle_rbp_command)
3824 {
3825         if (CMD_ARGC != 1)
3826                 return ERROR_COMMAND_SYNTAX_ERROR;
3827
3828         target_addr_t addr;
3829         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], addr);
3830
3831         struct target *target = get_current_target(CMD_CTX);
3832         breakpoint_remove(target, addr);
3833
3834         return ERROR_OK;
3835 }
3836
3837 COMMAND_HANDLER(handle_wp_command)
3838 {
3839         struct target *target = get_current_target(CMD_CTX);
3840
3841         if (CMD_ARGC == 0) {
3842                 struct watchpoint *watchpoint = target->watchpoints;
3843
3844                 while (watchpoint) {
3845                         command_print(CMD, "address: " TARGET_ADDR_FMT
3846                                         ", len: 0x%8.8" PRIx32
3847                                         ", r/w/a: %i, value: 0x%8.8" PRIx32
3848                                         ", mask: 0x%8.8" PRIx32,
3849                                         watchpoint->address,
3850                                         watchpoint->length,
3851                                         (int)watchpoint->rw,
3852                                         watchpoint->value,
3853                                         watchpoint->mask);
3854                         watchpoint = watchpoint->next;
3855                 }
3856                 return ERROR_OK;
3857         }
3858
3859         enum watchpoint_rw type = WPT_ACCESS;
3860         uint32_t addr = 0;
3861         uint32_t length = 0;
3862         uint32_t data_value = 0x0;
3863         uint32_t data_mask = 0xffffffff;
3864
3865         switch (CMD_ARGC) {
3866         case 5:
3867                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
3868                 /* fall through */
3869         case 4:
3870                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
3871                 /* fall through */
3872         case 3:
3873                 switch (CMD_ARGV[2][0]) {
3874                 case 'r':
3875                         type = WPT_READ;
3876                         break;
3877                 case 'w':
3878                         type = WPT_WRITE;
3879                         break;
3880                 case 'a':
3881                         type = WPT_ACCESS;
3882                         break;
3883                 default:
3884                         LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
3885                         return ERROR_COMMAND_SYNTAX_ERROR;
3886                 }
3887                 /* fall through */
3888         case 2:
3889                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
3890                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3891                 break;
3892
3893         default:
3894                 return ERROR_COMMAND_SYNTAX_ERROR;
3895         }
3896
3897         int retval = watchpoint_add(target, addr, length, type,
3898                         data_value, data_mask);
3899         if (ERROR_OK != retval)
3900                 LOG_ERROR("Failure setting watchpoints");
3901
3902         return retval;
3903 }
3904
3905 COMMAND_HANDLER(handle_rwp_command)
3906 {
3907         if (CMD_ARGC != 1)
3908                 return ERROR_COMMAND_SYNTAX_ERROR;
3909
3910         uint32_t addr;
3911         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
3912
3913         struct target *target = get_current_target(CMD_CTX);
3914         watchpoint_remove(target, addr);
3915
3916         return ERROR_OK;
3917 }
3918
3919 /**
3920  * Translate a virtual address to a physical address.
3921  *
3922  * The low-level target implementation must have logged a detailed error
3923  * which is forwarded to telnet/GDB session.
3924  */
3925 COMMAND_HANDLER(handle_virt2phys_command)
3926 {
3927         if (CMD_ARGC != 1)
3928                 return ERROR_COMMAND_SYNTAX_ERROR;
3929
3930         target_addr_t va;
3931         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], va);
3932         target_addr_t pa;
3933
3934         struct target *target = get_current_target(CMD_CTX);
3935         int retval = target->type->virt2phys(target, va, &pa);
3936         if (retval == ERROR_OK)
3937                 command_print(CMD, "Physical address " TARGET_ADDR_FMT "", pa);
3938
3939         return retval;
3940 }
3941
3942 static void writeData(FILE *f, const void *data, size_t len)
3943 {
3944         size_t written = fwrite(data, 1, len, f);
3945         if (written != len)
3946                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3947 }
3948
3949 static void writeLong(FILE *f, int l, struct target *target)
3950 {
3951         uint8_t val[4];
3952
3953         target_buffer_set_u32(target, val, l);
3954         writeData(f, val, 4);
3955 }
3956
3957 static void writeString(FILE *f, char *s)
3958 {
3959         writeData(f, s, strlen(s));
3960 }
3961
3962 typedef unsigned char UNIT[2];  /* unit of profiling */
3963
3964 /* Dump a gmon.out histogram file. */
3965 static void write_gmon(uint32_t *samples, uint32_t sampleNum, const char *filename, bool with_range,
3966                         uint32_t start_address, uint32_t end_address, struct target *target, uint32_t duration_ms)
3967 {
3968         uint32_t i;
3969         FILE *f = fopen(filename, "w");
3970         if (f == NULL)
3971                 return;
3972         writeString(f, "gmon");
3973         writeLong(f, 0x00000001, target); /* Version */
3974         writeLong(f, 0, target); /* padding */
3975         writeLong(f, 0, target); /* padding */
3976         writeLong(f, 0, target); /* padding */
3977
3978         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
3979         writeData(f, &zero, 1);
3980
3981         /* figure out bucket size */
3982         uint32_t min;
3983         uint32_t max;
3984         if (with_range) {
3985                 min = start_address;
3986                 max = end_address;
3987         } else {
3988                 min = samples[0];
3989                 max = samples[0];
3990                 for (i = 0; i < sampleNum; i++) {
3991                         if (min > samples[i])
3992                                 min = samples[i];
3993                         if (max < samples[i])
3994                                 max = samples[i];
3995                 }
3996
3997                 /* max should be (largest sample + 1)
3998                  * Refer to binutils/gprof/hist.c (find_histogram_for_pc) */
3999                 max++;
4000         }
4001
4002         int addressSpace = max - min;
4003         assert(addressSpace >= 2);
4004
4005         /* FIXME: What is the reasonable number of buckets?
4006          * The profiling result will be more accurate if there are enough buckets. */
4007         static const uint32_t maxBuckets = 128 * 1024; /* maximum buckets. */
4008         uint32_t numBuckets = addressSpace / sizeof(UNIT);
4009         if (numBuckets > maxBuckets)
4010                 numBuckets = maxBuckets;
4011         int *buckets = malloc(sizeof(int) * numBuckets);
4012         if (buckets == NULL) {
4013                 fclose(f);
4014                 return;
4015         }
4016         memset(buckets, 0, sizeof(int) * numBuckets);
4017         for (i = 0; i < sampleNum; i++) {
4018                 uint32_t address = samples[i];
4019
4020                 if ((address < min) || (max <= address))
4021                         continue;
4022
4023                 long long a = address - min;
4024                 long long b = numBuckets;
4025                 long long c = addressSpace;
4026                 int index_t = (a * b) / c; /* danger!!!! int32 overflows */
4027                 buckets[index_t]++;
4028         }
4029
4030         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
4031         writeLong(f, min, target);                      /* low_pc */
4032         writeLong(f, max, target);                      /* high_pc */
4033         writeLong(f, numBuckets, target);       /* # of buckets */
4034         float sample_rate = sampleNum / (duration_ms / 1000.0);
4035         writeLong(f, sample_rate, target);
4036         writeString(f, "seconds");
4037         for (i = 0; i < (15-strlen("seconds")); i++)
4038                 writeData(f, &zero, 1);
4039         writeString(f, "s");
4040
4041         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
4042
4043         char *data = malloc(2 * numBuckets);
4044         if (data != NULL) {
4045                 for (i = 0; i < numBuckets; i++) {
4046                         int val;
4047                         val = buckets[i];
4048                         if (val > 65535)
4049                                 val = 65535;
4050                         data[i * 2] = val&0xff;
4051                         data[i * 2 + 1] = (val >> 8) & 0xff;
4052                 }
4053                 free(buckets);
4054                 writeData(f, data, numBuckets * 2);
4055                 free(data);
4056         } else
4057                 free(buckets);
4058
4059         fclose(f);
4060 }
4061
4062 /* profiling samples the CPU PC as quickly as OpenOCD is able,
4063  * which will be used as a random sampling of PC */
4064 COMMAND_HANDLER(handle_profile_command)
4065 {
4066         struct target *target = get_current_target(CMD_CTX);
4067
4068         if ((CMD_ARGC != 2) && (CMD_ARGC != 4))
4069                 return ERROR_COMMAND_SYNTAX_ERROR;
4070
4071         const uint32_t MAX_PROFILE_SAMPLE_NUM = 10000;
4072         uint32_t offset;
4073         uint32_t num_of_samples;
4074         int retval = ERROR_OK;
4075
4076         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], offset);
4077
4078         uint32_t *samples = malloc(sizeof(uint32_t) * MAX_PROFILE_SAMPLE_NUM);
4079         if (samples == NULL) {
4080                 LOG_ERROR("No memory to store samples.");
4081                 return ERROR_FAIL;
4082         }
4083
4084         uint64_t timestart_ms = timeval_ms();
4085         /**
4086          * Some cores let us sample the PC without the
4087          * annoying halt/resume step; for example, ARMv7 PCSR.
4088          * Provide a way to use that more efficient mechanism.
4089          */
4090         retval = target_profiling(target, samples, MAX_PROFILE_SAMPLE_NUM,
4091                                 &num_of_samples, offset);
4092         if (retval != ERROR_OK) {
4093                 free(samples);
4094                 return retval;
4095         }
4096         uint32_t duration_ms = timeval_ms() - timestart_ms;
4097
4098         assert(num_of_samples <= MAX_PROFILE_SAMPLE_NUM);
4099
4100         retval = target_poll(target);
4101         if (retval != ERROR_OK) {
4102                 free(samples);
4103                 return retval;
4104         }
4105         if (target->state == TARGET_RUNNING) {
4106                 retval = target_halt(target);
4107                 if (retval != ERROR_OK) {
4108                         free(samples);
4109                         return retval;
4110                 }
4111         }
4112
4113         retval = target_poll(target);
4114         if (retval != ERROR_OK) {
4115                 free(samples);
4116                 return retval;
4117         }
4118
4119         uint32_t start_address = 0;
4120         uint32_t end_address = 0;
4121         bool with_range = false;
4122         if (CMD_ARGC == 4) {
4123                 with_range = true;
4124                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], start_address);
4125                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], end_address);
4126         }
4127
4128         write_gmon(samples, num_of_samples, CMD_ARGV[1],
4129                    with_range, start_address, end_address, target, duration_ms);
4130         command_print(CMD, "Wrote %s", CMD_ARGV[1]);
4131
4132         free(samples);
4133         return retval;
4134 }
4135
4136 static int new_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t val)
4137 {
4138         char *namebuf;
4139         Jim_Obj *nameObjPtr, *valObjPtr;
4140         int result;
4141
4142         namebuf = alloc_printf("%s(%d)", varname, idx);
4143         if (!namebuf)
4144                 return JIM_ERR;
4145
4146         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4147         valObjPtr = Jim_NewIntObj(interp, val);
4148         if (!nameObjPtr || !valObjPtr) {
4149                 free(namebuf);
4150                 return JIM_ERR;
4151         }
4152
4153         Jim_IncrRefCount(nameObjPtr);
4154         Jim_IncrRefCount(valObjPtr);
4155         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
4156         Jim_DecrRefCount(interp, nameObjPtr);
4157         Jim_DecrRefCount(interp, valObjPtr);
4158         free(namebuf);
4159         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
4160         return result;
4161 }
4162
4163 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4164 {
4165         struct command_context *context;
4166         struct target *target;
4167
4168         context = current_command_context(interp);
4169         assert(context != NULL);
4170
4171         target = get_current_target(context);
4172         if (target == NULL) {
4173                 LOG_ERROR("mem2array: no current target");
4174                 return JIM_ERR;
4175         }
4176
4177         return target_mem2array(interp, target, argc - 1, argv + 1);
4178 }
4179
4180 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
4181 {
4182         long l;
4183         uint32_t width;
4184         int len;
4185         uint32_t addr;
4186         uint32_t count;
4187         uint32_t v;
4188         const char *varname;
4189         const char *phys;
4190         bool is_phys;
4191         int  n, e, retval;
4192         uint32_t i;
4193
4194         /* argv[1] = name of array to receive the data
4195          * argv[2] = desired width
4196          * argv[3] = memory address
4197          * argv[4] = count of times to read
4198          */
4199
4200         if (argc < 4 || argc > 5) {
4201                 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4202                 return JIM_ERR;
4203         }
4204         varname = Jim_GetString(argv[0], &len);
4205         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4206
4207         e = Jim_GetLong(interp, argv[1], &l);
4208         width = l;
4209         if (e != JIM_OK)
4210                 return e;
4211
4212         e = Jim_GetLong(interp, argv[2], &l);
4213         addr = l;
4214         if (e != JIM_OK)
4215                 return e;
4216         e = Jim_GetLong(interp, argv[3], &l);
4217         len = l;
4218         if (e != JIM_OK)
4219                 return e;
4220         is_phys = false;
4221         if (argc > 4) {
4222                 phys = Jim_GetString(argv[4], &n);
4223                 if (!strncmp(phys, "phys", n))
4224                         is_phys = true;
4225                 else
4226                         return JIM_ERR;
4227         }
4228         switch (width) {
4229                 case 8:
4230                         width = 1;
4231                         break;
4232                 case 16:
4233                         width = 2;
4234                         break;
4235                 case 32:
4236                         width = 4;
4237                         break;
4238                 default:
4239                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4240                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
4241                         return JIM_ERR;
4242         }
4243         if (len == 0) {
4244                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4245                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
4246                 return JIM_ERR;
4247         }
4248         if ((addr + (len * width)) < addr) {
4249                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4250                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
4251                 return JIM_ERR;
4252         }
4253         /* absurd transfer size? */
4254         if (len > 65536) {
4255                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4256                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
4257                 return JIM_ERR;
4258         }
4259
4260         if ((width == 1) ||
4261                 ((width == 2) && ((addr & 1) == 0)) ||
4262                 ((width == 4) && ((addr & 3) == 0))) {
4263                 /* all is well */
4264         } else {
4265                 char buf[100];
4266                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4267                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4268                                 addr,
4269                                 width);
4270                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4271                 return JIM_ERR;
4272         }
4273
4274         /* Transfer loop */
4275
4276         /* index counter */
4277         n = 0;
4278
4279         size_t buffersize = 4096;
4280         uint8_t *buffer = malloc(buffersize);
4281         if (buffer == NULL)
4282                 return JIM_ERR;
4283
4284         /* assume ok */
4285         e = JIM_OK;
4286         while (len) {
4287                 /* Slurp... in buffer size chunks */
4288
4289                 count = len; /* in objects.. */
4290                 if (count > (buffersize / width))
4291                         count = (buffersize / width);
4292
4293                 if (is_phys)
4294                         retval = target_read_phys_memory(target, addr, width, count, buffer);
4295                 else
4296                         retval = target_read_memory(target, addr, width, count, buffer);
4297                 if (retval != ERROR_OK) {
4298                         /* BOO !*/
4299                         LOG_ERROR("mem2array: Read @ 0x%08" PRIx32 ", w=%" PRId32 ", cnt=%" PRId32 ", failed",
4300                                           addr,
4301                                           width,
4302                                           count);
4303                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4304                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
4305                         e = JIM_ERR;
4306                         break;
4307                 } else {
4308                         v = 0; /* shut up gcc */
4309                         for (i = 0; i < count ; i++, n++) {
4310                                 switch (width) {
4311                                         case 4:
4312                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
4313                                                 break;
4314                                         case 2:
4315                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
4316                                                 break;
4317                                         case 1:
4318                                                 v = buffer[i] & 0x0ff;
4319                                                 break;
4320                                 }
4321                                 new_int_array_element(interp, varname, n, v);
4322                         }
4323                         len -= count;
4324                         addr += count * width;
4325                 }
4326         }
4327
4328         free(buffer);
4329
4330         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4331
4332         return e;
4333 }
4334
4335 static int get_int_array_element(Jim_Interp *interp, const char *varname, int idx, uint32_t *val)
4336 {
4337         char *namebuf;
4338         Jim_Obj *nameObjPtr, *valObjPtr;
4339         int result;
4340         long l;
4341
4342         namebuf = alloc_printf("%s(%d)", varname, idx);
4343         if (!namebuf)
4344                 return JIM_ERR;
4345
4346         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
4347         if (!nameObjPtr) {
4348                 free(namebuf);
4349                 return JIM_ERR;
4350         }
4351
4352         Jim_IncrRefCount(nameObjPtr);
4353         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
4354         Jim_DecrRefCount(interp, nameObjPtr);
4355         free(namebuf);
4356         if (valObjPtr == NULL)
4357                 return JIM_ERR;
4358
4359         result = Jim_GetLong(interp, valObjPtr, &l);
4360         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
4361         *val = l;
4362         return result;
4363 }
4364
4365 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4366 {
4367         struct command_context *context;
4368         struct target *target;
4369
4370         context = current_command_context(interp);
4371         assert(context != NULL);
4372
4373         target = get_current_target(context);
4374         if (target == NULL) {
4375                 LOG_ERROR("array2mem: no current target");
4376                 return JIM_ERR;
4377         }
4378
4379         return target_array2mem(interp, target, argc-1, argv + 1);
4380 }
4381
4382 static int target_array2mem(Jim_Interp *interp, struct target *target,
4383                 int argc, Jim_Obj *const *argv)
4384 {
4385         long l;
4386         uint32_t width;
4387         int len;
4388         uint32_t addr;
4389         uint32_t count;
4390         uint32_t v;
4391         const char *varname;
4392         const char *phys;
4393         bool is_phys;
4394         int  n, e, retval;
4395         uint32_t i;
4396
4397         /* argv[1] = name of array to get the data
4398          * argv[2] = desired width
4399          * argv[3] = memory address
4400          * argv[4] = count to write
4401          */
4402         if (argc < 4 || argc > 5) {
4403                 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems [phys]");
4404                 return JIM_ERR;
4405         }
4406         varname = Jim_GetString(argv[0], &len);
4407         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
4408
4409         e = Jim_GetLong(interp, argv[1], &l);
4410         width = l;
4411         if (e != JIM_OK)
4412                 return e;
4413
4414         e = Jim_GetLong(interp, argv[2], &l);
4415         addr = l;
4416         if (e != JIM_OK)
4417                 return e;
4418         e = Jim_GetLong(interp, argv[3], &l);
4419         len = l;
4420         if (e != JIM_OK)
4421                 return e;
4422         is_phys = false;
4423         if (argc > 4) {
4424                 phys = Jim_GetString(argv[4], &n);
4425                 if (!strncmp(phys, "phys", n))
4426                         is_phys = true;
4427                 else
4428                         return JIM_ERR;
4429         }
4430         switch (width) {
4431                 case 8:
4432                         width = 1;
4433                         break;
4434                 case 16:
4435                         width = 2;
4436                         break;
4437                 case 32:
4438                         width = 4;
4439                         break;
4440                 default:
4441                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4442                         Jim_AppendStrings(interp, Jim_GetResult(interp),
4443                                         "Invalid width param, must be 8/16/32", NULL);
4444                         return JIM_ERR;
4445         }
4446         if (len == 0) {
4447                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4448                 Jim_AppendStrings(interp, Jim_GetResult(interp),
4449                                 "array2mem: zero width read?", NULL);
4450                 return JIM_ERR;
4451         }
4452         if ((addr + (len * width)) < addr) {
4453                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4454                 Jim_AppendStrings(interp, Jim_GetResult(interp),
4455                                 "array2mem: addr + len - wraps to zero?", NULL);
4456                 return JIM_ERR;
4457         }
4458         /* absurd transfer size? */
4459         if (len > 65536) {
4460                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4461                 Jim_AppendStrings(interp, Jim_GetResult(interp),
4462                                 "array2mem: absurd > 64K item request", NULL);
4463                 return JIM_ERR;
4464         }
4465
4466         if ((width == 1) ||
4467                 ((width == 2) && ((addr & 1) == 0)) ||
4468                 ((width == 4) && ((addr & 3) == 0))) {
4469                 /* all is well */
4470         } else {
4471                 char buf[100];
4472                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4473                 sprintf(buf, "array2mem address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
4474                                 addr,
4475                                 width);
4476                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf, NULL);
4477                 return JIM_ERR;
4478         }
4479
4480         /* Transfer loop */
4481
4482         /* index counter */
4483         n = 0;
4484         /* assume ok */
4485         e = JIM_OK;
4486
4487         size_t buffersize = 4096;
4488         uint8_t *buffer = malloc(buffersize);
4489         if (buffer == NULL)
4490                 return JIM_ERR;
4491
4492         while (len) {
4493                 /* Slurp... in buffer size chunks */
4494
4495                 count = len; /* in objects.. */
4496                 if (count > (buffersize / width))
4497                         count = (buffersize / width);
4498
4499                 v = 0; /* shut up gcc */
4500                 for (i = 0; i < count; i++, n++) {
4501                         get_int_array_element(interp, varname, n, &v);
4502                         switch (width) {
4503                         case 4:
4504                                 target_buffer_set_u32(target, &buffer[i * width], v);
4505                                 break;
4506                         case 2:
4507                                 target_buffer_set_u16(target, &buffer[i * width], v);
4508                                 break;
4509                         case 1:
4510                                 buffer[i] = v & 0x0ff;
4511                                 break;
4512                         }
4513                 }
4514                 len -= count;
4515
4516                 if (is_phys)
4517                         retval = target_write_phys_memory(target, addr, width, count, buffer);
4518                 else
4519                         retval = target_write_memory(target, addr, width, count, buffer);
4520                 if (retval != ERROR_OK) {
4521                         /* BOO !*/
4522                         LOG_ERROR("array2mem: Write @ 0x%08" PRIx32 ", w=%" PRId32 ", cnt=%" PRId32 ", failed",
4523                                           addr,
4524                                           width,
4525                                           count);
4526                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4527                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
4528                         e = JIM_ERR;
4529                         break;
4530                 }
4531                 addr += count * width;
4532         }
4533
4534         free(buffer);
4535
4536         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
4537
4538         return e;
4539 }
4540
4541 /* FIX? should we propagate errors here rather than printing them
4542  * and continuing?
4543  */
4544 void target_handle_event(struct target *target, enum target_event e)
4545 {
4546         struct target_event_action *teap;
4547         int retval;
4548
4549         for (teap = target->event_action; teap != NULL; teap = teap->next) {
4550                 if (teap->event == e) {
4551                         LOG_DEBUG("target(%d): %s (%s) event: %d (%s) action: %s",
4552                                            target->target_number,
4553                                            target_name(target),
4554                                            target_type_name(target),
4555                                            e,
4556                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4557                                            Jim_GetString(teap->body, NULL));
4558
4559                         /* Override current target by the target an event
4560                          * is issued from (lot of scripts need it).
4561                          * Return back to previous override as soon
4562                          * as the handler processing is done */
4563                         struct command_context *cmd_ctx = current_command_context(teap->interp);
4564                         struct target *saved_target_override = cmd_ctx->current_target_override;
4565                         cmd_ctx->current_target_override = target;
4566                         retval = Jim_EvalObj(teap->interp, teap->body);
4567
4568                         if (retval == JIM_RETURN)
4569                                 retval = teap->interp->returnCode;
4570
4571                         if (retval != JIM_OK) {
4572                                 Jim_MakeErrorMessage(teap->interp);
4573                                 LOG_USER("Error executing event %s on target %s:\n%s",
4574                                                   Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
4575                                                   target_name(target),
4576                                                   Jim_GetString(Jim_GetResult(teap->interp), NULL));
4577                                 /* clean both error code and stacktrace before return */
4578                                 Jim_Eval(teap->interp, "error \"\" \"\"");
4579                         }
4580
4581                         cmd_ctx->current_target_override = saved_target_override;
4582                 }
4583         }
4584 }
4585
4586 /**
4587  * Returns true only if the target has a handler for the specified event.
4588  */
4589 bool target_has_event_action(struct target *target, enum target_event event)
4590 {
4591         struct target_event_action *teap;
4592
4593         for (teap = target->event_action; teap != NULL; teap = teap->next) {
4594                 if (teap->event == event)
4595                         return true;
4596         }
4597         return false;
4598 }
4599
4600 enum target_cfg_param {
4601         TCFG_TYPE,
4602         TCFG_EVENT,
4603         TCFG_WORK_AREA_VIRT,
4604         TCFG_WORK_AREA_PHYS,
4605         TCFG_WORK_AREA_SIZE,
4606         TCFG_WORK_AREA_BACKUP,
4607         TCFG_ENDIAN,
4608         TCFG_COREID,
4609         TCFG_CHAIN_POSITION,
4610         TCFG_DBGBASE,
4611         TCFG_RTOS,
4612         TCFG_DEFER_EXAMINE,
4613         TCFG_GDB_PORT,
4614 };
4615
4616 static Jim_Nvp nvp_config_opts[] = {
4617         { .name = "-type",             .value = TCFG_TYPE },
4618         { .name = "-event",            .value = TCFG_EVENT },
4619         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
4620         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
4621         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
4622         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
4623         { .name = "-endian" ,          .value = TCFG_ENDIAN },
4624         { .name = "-coreid",           .value = TCFG_COREID },
4625         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
4626         { .name = "-dbgbase",          .value = TCFG_DBGBASE },
4627         { .name = "-rtos",             .value = TCFG_RTOS },
4628         { .name = "-defer-examine",    .value = TCFG_DEFER_EXAMINE },
4629         { .name = "-gdb-port",         .value = TCFG_GDB_PORT },
4630         { .name = NULL, .value = -1 }
4631 };
4632
4633 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
4634 {
4635         Jim_Nvp *n;
4636         Jim_Obj *o;
4637         jim_wide w;
4638         int e;
4639
4640         /* parse config or cget options ... */
4641         while (goi->argc > 0) {
4642                 Jim_SetEmptyResult(goi->interp);
4643                 /* Jim_GetOpt_Debug(goi); */
4644
4645                 if (target->type->target_jim_configure) {
4646                         /* target defines a configure function */
4647                         /* target gets first dibs on parameters */
4648                         e = (*(target->type->target_jim_configure))(target, goi);
4649                         if (e == JIM_OK) {
4650                                 /* more? */
4651                                 continue;
4652                         }
4653                         if (e == JIM_ERR) {
4654                                 /* An error */
4655                                 return e;
4656                         }
4657                         /* otherwise we 'continue' below */
4658                 }
4659                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
4660                 if (e != JIM_OK) {
4661                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
4662                         return e;
4663                 }
4664                 switch (n->value) {
4665                 case TCFG_TYPE:
4666                         /* not setable */
4667                         if (goi->isconfigure) {
4668                                 Jim_SetResultFormatted(goi->interp,
4669                                                 "not settable: %s", n->name);
4670                                 return JIM_ERR;
4671                         } else {
4672 no_params:
4673                                 if (goi->argc != 0) {
4674                                         Jim_WrongNumArgs(goi->interp,
4675                                                         goi->argc, goi->argv,
4676                                                         "NO PARAMS");
4677                                         return JIM_ERR;
4678                                 }
4679                         }
4680                         Jim_SetResultString(goi->interp,
4681                                         target_type_name(target), -1);
4682                         /* loop for more */
4683                         break;
4684                 case TCFG_EVENT:
4685                         if (goi->argc == 0) {
4686                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
4687                                 return JIM_ERR;
4688                         }
4689
4690                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
4691                         if (e != JIM_OK) {
4692                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
4693                                 return e;
4694                         }
4695
4696                         if (goi->isconfigure) {
4697                                 if (goi->argc != 1) {
4698                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
4699                                         return JIM_ERR;
4700                                 }
4701                         } else {
4702                                 if (goi->argc != 0) {
4703                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
4704                                         return JIM_ERR;
4705                                 }
4706                         }
4707
4708                         {
4709                                 struct target_event_action *teap;
4710
4711                                 teap = target->event_action;
4712                                 /* replace existing? */
4713                                 while (teap) {
4714                                         if (teap->event == (enum target_event)n->value)
4715                                                 break;
4716                                         teap = teap->next;
4717                                 }
4718
4719                                 if (goi->isconfigure) {
4720                                         bool replace = true;
4721                                         if (teap == NULL) {
4722                                                 /* create new */
4723                                                 teap = calloc(1, sizeof(*teap));
4724                                                 replace = false;
4725                                         }
4726                                         teap->event = n->value;
4727                                         teap->interp = goi->interp;
4728                                         Jim_GetOpt_Obj(goi, &o);
4729                                         if (teap->body)
4730                                                 Jim_DecrRefCount(teap->interp, teap->body);
4731                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
4732                                         /*
4733                                          * FIXME:
4734                                          *     Tcl/TK - "tk events" have a nice feature.
4735                                          *     See the "BIND" command.
4736                                          *    We should support that here.
4737                                          *     You can specify %X and %Y in the event code.
4738                                          *     The idea is: %T - target name.
4739                                          *     The idea is: %N - target number
4740                                          *     The idea is: %E - event name.
4741                                          */
4742                                         Jim_IncrRefCount(teap->body);
4743
4744                                         if (!replace) {
4745                                                 /* add to head of event list */
4746                                                 teap->next = target->event_action;
4747                                                 target->event_action = teap;
4748                                         }
4749                                         Jim_SetEmptyResult(goi->interp);
4750                                 } else {
4751                                         /* get */
4752                                         if (teap == NULL)
4753                                                 Jim_SetEmptyResult(goi->interp);
4754                                         else
4755                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
4756                                 }
4757                         }
4758                         /* loop for more */
4759                         break;
4760
4761                 case TCFG_WORK_AREA_VIRT:
4762                         if (goi->isconfigure) {
4763                                 target_free_all_working_areas(target);
4764                                 e = Jim_GetOpt_Wide(goi, &w);
4765                                 if (e != JIM_OK)
4766                                         return e;
4767                                 target->working_area_virt = w;
4768                                 target->working_area_virt_spec = true;
4769                         } else {
4770                                 if (goi->argc != 0)
4771                                         goto no_params;
4772                         }
4773                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
4774                         /* loop for more */
4775                         break;
4776
4777                 case TCFG_WORK_AREA_PHYS:
4778                         if (goi->isconfigure) {
4779                                 target_free_all_working_areas(target);
4780                                 e = Jim_GetOpt_Wide(goi, &w);
4781                                 if (e != JIM_OK)
4782                                         return e;
4783                                 target->working_area_phys = w;
4784                                 target->working_area_phys_spec = true;
4785                         } else {
4786                                 if (goi->argc != 0)
4787                                         goto no_params;
4788                         }
4789                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
4790                         /* loop for more */
4791                         break;
4792
4793                 case TCFG_WORK_AREA_SIZE:
4794                         if (goi->isconfigure) {
4795                                 target_free_all_working_areas(target);
4796                                 e = Jim_GetOpt_Wide(goi, &w);
4797                                 if (e != JIM_OK)
4798                                         return e;
4799                                 target->working_area_size = w;
4800                         } else {
4801                                 if (goi->argc != 0)
4802                                         goto no_params;
4803                         }
4804                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
4805                         /* loop for more */
4806                         break;
4807
4808                 case TCFG_WORK_AREA_BACKUP:
4809                         if (goi->isconfigure) {
4810                                 target_free_all_working_areas(target);
4811                                 e = Jim_GetOpt_Wide(goi, &w);
4812                                 if (e != JIM_OK)
4813                                         return e;
4814                                 /* make this exactly 1 or 0 */
4815                                 target->backup_working_area = (!!w);
4816                         } else {
4817                                 if (goi->argc != 0)
4818                                         goto no_params;
4819                         }
4820                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
4821                         /* loop for more e*/
4822                         break;
4823
4824
4825                 case TCFG_ENDIAN:
4826                         if (goi->isconfigure) {
4827                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
4828                                 if (e != JIM_OK) {
4829                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
4830                                         return e;
4831                                 }
4832                                 target->endianness = n->value;
4833                         } else {
4834                                 if (goi->argc != 0)
4835                                         goto no_params;
4836                         }
4837                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4838                         if (n->name == NULL) {
4839                                 target->endianness = TARGET_LITTLE_ENDIAN;
4840                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
4841                         }
4842                         Jim_SetResultString(goi->interp, n->name, -1);
4843                         /* loop for more */
4844                         break;
4845
4846                 case TCFG_COREID:
4847                         if (goi->isconfigure) {
4848                                 e = Jim_GetOpt_Wide(goi, &w);
4849                                 if (e != JIM_OK)
4850                                         return e;
4851                                 target->coreid = (int32_t)w;
4852                         } else {
4853                                 if (goi->argc != 0)
4854                                         goto no_params;
4855                         }
4856                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->coreid));
4857                         /* loop for more */
4858                         break;
4859
4860                 case TCFG_CHAIN_POSITION:
4861                         if (goi->isconfigure) {
4862                                 Jim_Obj *o_t;
4863                                 struct jtag_tap *tap;
4864
4865                                 if (target->has_dap) {
4866                                         Jim_SetResultString(goi->interp,
4867                                                 "target requires -dap parameter instead of -chain-position!", -1);
4868                                         return JIM_ERR;
4869                                 }
4870
4871                                 target_free_all_working_areas(target);
4872                                 e = Jim_GetOpt_Obj(goi, &o_t);
4873                                 if (e != JIM_OK)
4874                                         return e;
4875                                 tap = jtag_tap_by_jim_obj(goi->interp, o_t);
4876                                 if (tap == NULL)
4877                                         return JIM_ERR;
4878                                 target->tap = tap;
4879                                 target->tap_configured = true;
4880                         } else {
4881                                 if (goi->argc != 0)
4882                                         goto no_params;
4883                         }
4884                         Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
4885                         /* loop for more e*/
4886                         break;
4887                 case TCFG_DBGBASE:
4888                         if (goi->isconfigure) {
4889                                 e = Jim_GetOpt_Wide(goi, &w);
4890                                 if (e != JIM_OK)
4891                                         return e;
4892                                 target->dbgbase = (uint32_t)w;
4893                                 target->dbgbase_set = true;
4894                         } else {
4895                                 if (goi->argc != 0)
4896                                         goto no_params;
4897                         }
4898                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->dbgbase));
4899                         /* loop for more */
4900                         break;
4901                 case TCFG_RTOS:
4902                         /* RTOS */
4903                         {
4904                                 int result = rtos_create(goi, target);
4905                                 if (result != JIM_OK)
4906                                         return result;
4907                         }
4908                         /* loop for more */
4909                         break;
4910
4911                 case TCFG_DEFER_EXAMINE:
4912                         /* DEFER_EXAMINE */
4913                         target->defer_examine = true;
4914                         /* loop for more */
4915                         break;
4916
4917                 case TCFG_GDB_PORT:
4918                         if (goi->isconfigure) {
4919                                 struct command_context *cmd_ctx = current_command_context(goi->interp);
4920                                 if (cmd_ctx->mode != COMMAND_CONFIG) {
4921                                         Jim_SetResultString(goi->interp, "-gdb-port must be configured before 'init'", -1);
4922                                         return JIM_ERR;
4923                                 }
4924
4925                                 const char *s;
4926                                 e = Jim_GetOpt_String(goi, &s, NULL);
4927                                 if (e != JIM_OK)
4928                                         return e;
4929                                 target->gdb_port_override = strdup(s);
4930                         } else {
4931                                 if (goi->argc != 0)
4932                                         goto no_params;
4933                         }
4934                         Jim_SetResultString(goi->interp, target->gdb_port_override ? : "undefined", -1);
4935                         /* loop for more */
4936                         break;
4937                 }
4938         } /* while (goi->argc) */
4939
4940
4941                 /* done - we return */
4942         return JIM_OK;
4943 }
4944
4945 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
4946 {
4947         Jim_GetOptInfo goi;
4948
4949         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4950         goi.isconfigure = !strcmp(Jim_GetString(argv[0], NULL), "configure");
4951         if (goi.argc < 1) {
4952                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4953                                  "missing: -option ...");
4954                 return JIM_ERR;
4955         }
4956         struct target *target = Jim_CmdPrivData(goi.interp);
4957         return target_configure(&goi, target);
4958 }
4959
4960 static int jim_target_mem2array(Jim_Interp *interp,
4961                 int argc, Jim_Obj *const *argv)
4962 {
4963         struct target *target = Jim_CmdPrivData(interp);
4964         return target_mem2array(interp, target, argc - 1, argv + 1);
4965 }
4966
4967 static int jim_target_array2mem(Jim_Interp *interp,
4968                 int argc, Jim_Obj *const *argv)
4969 {
4970         struct target *target = Jim_CmdPrivData(interp);
4971         return target_array2mem(interp, target, argc - 1, argv + 1);
4972 }
4973
4974 static int jim_target_tap_disabled(Jim_Interp *interp)
4975 {
4976         Jim_SetResultFormatted(interp, "[TAP is disabled]");
4977         return JIM_ERR;
4978 }
4979
4980 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4981 {
4982         bool allow_defer = false;
4983
4984         Jim_GetOptInfo goi;
4985         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4986         if (goi.argc > 1) {
4987                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4988                 Jim_SetResultFormatted(goi.interp,
4989                                 "usage: %s ['allow-defer']", cmd_name);
4990                 return JIM_ERR;
4991         }
4992         if (goi.argc > 0 &&
4993             strcmp(Jim_GetString(argv[1], NULL), "allow-defer") == 0) {
4994                 /* consume it */
4995                 struct Jim_Obj *obj;
4996                 int e = Jim_GetOpt_Obj(&goi, &obj);
4997                 if (e != JIM_OK)
4998                         return e;
4999                 allow_defer = true;
5000         }
5001
5002         struct target *target = Jim_CmdPrivData(interp);
5003         if (!target->tap->enabled)
5004                 return jim_target_tap_disabled(interp);
5005
5006         if (allow_defer && target->defer_examine) {
5007                 LOG_INFO("Deferring arp_examine of %s", target_name(target));
5008                 LOG_INFO("Use arp_examine command to examine it manually!");
5009                 return JIM_OK;
5010         }
5011
5012         int e = target->type->examine(target);
5013         if (e != ERROR_OK)
5014                 return JIM_ERR;
5015         return JIM_OK;
5016 }
5017
5018 static int jim_target_was_examined(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5019 {
5020         struct target *target = Jim_CmdPrivData(interp);
5021
5022         Jim_SetResultBool(interp, target_was_examined(target));
5023         return JIM_OK;
5024 }
5025
5026 static int jim_target_examine_deferred(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
5027 {
5028         struct target *target = Jim_CmdPrivData(interp);
5029
5030         Jim_SetResultBool(interp, target->defer_examine);
5031         return JIM_OK;
5032 }
5033
5034 static int jim_target_halt_gdb(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5035 {
5036         if (argc != 1) {
5037                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5038                 return JIM_ERR;
5039         }
5040         struct target *target = Jim_CmdPrivData(interp);
5041
5042         if (target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT) != ERROR_OK)
5043                 return JIM_ERR;
5044
5045         return JIM_OK;
5046 }
5047
5048 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5049 {
5050         if (argc != 1) {
5051                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5052                 return JIM_ERR;
5053         }
5054         struct target *target = Jim_CmdPrivData(interp);
5055         if (!target->tap->enabled)
5056                 return jim_target_tap_disabled(interp);
5057
5058         int e;
5059         if (!(target_was_examined(target)))
5060                 e = ERROR_TARGET_NOT_EXAMINED;
5061         else
5062                 e = target->type->poll(target);
5063         if (e != ERROR_OK)
5064                 return JIM_ERR;
5065         return JIM_OK;
5066 }
5067
5068 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5069 {
5070         Jim_GetOptInfo goi;
5071         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5072
5073         if (goi.argc != 2) {
5074                 Jim_WrongNumArgs(interp, 0, argv,
5075                                 "([tT]|[fF]|assert|deassert) BOOL");
5076                 return JIM_ERR;
5077         }
5078
5079         Jim_Nvp *n;
5080         int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
5081         if (e != JIM_OK) {
5082                 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
5083                 return e;
5084         }
5085         /* the halt or not param */
5086         jim_wide a;
5087         e = Jim_GetOpt_Wide(&goi, &a);
5088         if (e != JIM_OK)
5089                 return e;
5090
5091         struct target *target = Jim_CmdPrivData(goi.interp);
5092         if (!target->tap->enabled)
5093                 return jim_target_tap_disabled(interp);
5094
5095         if (!target->type->assert_reset || !target->type->deassert_reset) {
5096                 Jim_SetResultFormatted(interp,
5097                                 "No target-specific reset for %s",
5098                                 target_name(target));
5099                 return JIM_ERR;
5100         }
5101
5102         if (target->defer_examine)
5103                 target_reset_examined(target);
5104
5105         /* determine if we should halt or not. */
5106         target->reset_halt = !!a;
5107         /* When this happens - all workareas are invalid. */
5108         target_free_all_working_areas_restore(target, 0);
5109
5110         /* do the assert */
5111         if (n->value == NVP_ASSERT)
5112                 e = target->type->assert_reset(target);
5113         else
5114                 e = target->type->deassert_reset(target);
5115         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5116 }
5117
5118 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5119 {
5120         if (argc != 1) {
5121                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5122                 return JIM_ERR;
5123         }
5124         struct target *target = Jim_CmdPrivData(interp);
5125         if (!target->tap->enabled)
5126                 return jim_target_tap_disabled(interp);
5127         int e = target->type->halt(target);
5128         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
5129 }
5130
5131 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5132 {
5133         Jim_GetOptInfo goi;
5134         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5135
5136         /* params:  <name>  statename timeoutmsecs */
5137         if (goi.argc != 2) {
5138                 const char *cmd_name = Jim_GetString(argv[0], NULL);
5139                 Jim_SetResultFormatted(goi.interp,
5140                                 "%s <state_name> <timeout_in_msec>", cmd_name);
5141                 return JIM_ERR;
5142         }
5143
5144         Jim_Nvp *n;
5145         int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
5146         if (e != JIM_OK) {
5147                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state, 1);
5148                 return e;
5149         }
5150         jim_wide a;
5151         e = Jim_GetOpt_Wide(&goi, &a);
5152         if (e != JIM_OK)
5153                 return e;
5154         struct target *target = Jim_CmdPrivData(interp);
5155         if (!target->tap->enabled)
5156                 return jim_target_tap_disabled(interp);
5157
5158         e = target_wait_state(target, n->value, a);
5159         if (e != ERROR_OK) {
5160                 Jim_Obj *eObj = Jim_NewIntObj(interp, e);
5161                 Jim_SetResultFormatted(goi.interp,
5162                                 "target: %s wait %s fails (%#s) %s",
5163                                 target_name(target), n->name,
5164                                 eObj, target_strerror_safe(e));
5165                 Jim_FreeNewObj(interp, eObj);
5166                 return JIM_ERR;
5167         }
5168         return JIM_OK;
5169 }
5170 /* List for human, Events defined for this target.
5171  * scripts/programs should use 'name cget -event NAME'
5172  */
5173 COMMAND_HANDLER(handle_target_event_list)
5174 {
5175         struct target *target = get_current_target(CMD_CTX);
5176         struct target_event_action *teap = target->event_action;
5177
5178         command_print(CMD, "Event actions for target (%d) %s\n",
5179                                    target->target_number,
5180                                    target_name(target));
5181         command_print(CMD, "%-25s | Body", "Event");
5182         command_print(CMD, "------------------------- | "
5183                         "----------------------------------------");
5184         while (teap) {
5185                 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
5186                 command_print(CMD, "%-25s | %s",
5187                                 opt->name, Jim_GetString(teap->body, NULL));
5188                 teap = teap->next;
5189         }
5190         command_print(CMD, "***END***");
5191         return ERROR_OK;
5192 }
5193 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5194 {
5195         if (argc != 1) {
5196                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
5197                 return JIM_ERR;
5198         }
5199         struct target *target = Jim_CmdPrivData(interp);
5200         Jim_SetResultString(interp, target_state_name(target), -1);
5201         return JIM_OK;
5202 }
5203 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5204 {
5205         Jim_GetOptInfo goi;
5206         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5207         if (goi.argc != 1) {
5208                 const char *cmd_name = Jim_GetString(argv[0], NULL);
5209                 Jim_SetResultFormatted(goi.interp, "%s <eventname>", cmd_name);
5210                 return JIM_ERR;
5211         }
5212         Jim_Nvp *n;
5213         int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
5214         if (e != JIM_OK) {
5215                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
5216                 return e;
5217         }
5218         struct target *target = Jim_CmdPrivData(interp);
5219         target_handle_event(target, n->value);
5220         return JIM_OK;
5221 }
5222
5223 static const struct command_registration target_instance_command_handlers[] = {
5224         {
5225                 .name = "configure",
5226                 .mode = COMMAND_ANY,
5227                 .jim_handler = jim_target_configure,
5228                 .help  = "configure a new target for use",
5229                 .usage = "[target_attribute ...]",
5230         },
5231         {
5232                 .name = "cget",
5233                 .mode = COMMAND_ANY,
5234                 .jim_handler = jim_target_configure,
5235                 .help  = "returns the specified target attribute",
5236                 .usage = "target_attribute",
5237         },
5238         {
5239                 .name = "mwd",
5240                 .handler = handle_mw_command,
5241                 .mode = COMMAND_EXEC,
5242                 .help = "Write 64-bit word(s) to target memory",
5243                 .usage = "address data [count]",
5244         },
5245         {
5246                 .name = "mww",
5247                 .handler = handle_mw_command,
5248                 .mode = COMMAND_EXEC,
5249                 .help = "Write 32-bit word(s) to target memory",
5250                 .usage = "address data [count]",
5251         },
5252         {
5253                 .name = "mwh",
5254                 .handler = handle_mw_command,
5255                 .mode = COMMAND_EXEC,
5256                 .help = "Write 16-bit half-word(s) to target memory",
5257                 .usage = "address data [count]",
5258         },
5259         {
5260                 .name = "mwb",
5261                 .handler = handle_mw_command,
5262                 .mode = COMMAND_EXEC,
5263                 .help = "Write byte(s) to target memory",
5264                 .usage = "address data [count]",
5265         },
5266         {
5267                 .name = "mdd",
5268                 .handler = handle_md_command,
5269                 .mode = COMMAND_EXEC,
5270                 .help = "Display target memory as 64-bit words",
5271                 .usage = "address [count]",
5272         },
5273         {
5274                 .name = "mdw",
5275                 .handler = handle_md_command,
5276                 .mode = COMMAND_EXEC,
5277                 .help = "Display target memory as 32-bit words",
5278                 .usage = "address [count]",
5279         },
5280         {
5281                 .name = "mdh",
5282                 .handler = handle_md_command,
5283                 .mode = COMMAND_EXEC,
5284                 .help = "Display target memory as 16-bit half-words",
5285                 .usage = "address [count]",
5286         },
5287         {
5288                 .name = "mdb",
5289                 .handler = handle_md_command,
5290                 .mode = COMMAND_EXEC,
5291                 .help = "Display target memory as 8-bit bytes",
5292                 .usage = "address [count]",
5293         },
5294         {
5295                 .name = "array2mem",
5296                 .mode = COMMAND_EXEC,
5297                 .jim_handler = jim_target_array2mem,
5298                 .help = "Writes Tcl array of 8/16/32 bit numbers "
5299                         "to target memory",
5300                 .usage = "arrayname bitwidth address count",
5301         },
5302         {
5303                 .name = "mem2array",
5304                 .mode = COMMAND_EXEC,
5305                 .jim_handler = jim_target_mem2array,
5306                 .help = "Loads Tcl array of 8/16/32 bit numbers "
5307                         "from target memory",
5308                 .usage = "arrayname bitwidth address count",
5309         },
5310         {
5311                 .name = "eventlist",
5312                 .handler = handle_target_event_list,
5313                 .mode = COMMAND_EXEC,
5314                 .help = "displays a table of events defined for this target",
5315                 .usage = "",
5316         },
5317         {
5318                 .name = "curstate",
5319                 .mode = COMMAND_EXEC,
5320                 .jim_handler = jim_target_current_state,
5321                 .help = "displays the current state of this target",
5322         },
5323         {
5324                 .name = "arp_examine",
5325                 .mode = COMMAND_EXEC,
5326                 .jim_handler = jim_target_examine,
5327                 .help = "used internally for reset processing",
5328                 .usage = "['allow-defer']",
5329         },
5330         {
5331                 .name = "was_examined",
5332                 .mode = COMMAND_EXEC,
5333                 .jim_handler = jim_target_was_examined,
5334                 .help = "used internally for reset processing",
5335         },
5336         {
5337                 .name = "examine_deferred",
5338                 .mode = COMMAND_EXEC,
5339                 .jim_handler = jim_target_examine_deferred,
5340                 .help = "used internally for reset processing",
5341         },
5342         {
5343                 .name = "arp_halt_gdb",
5344                 .mode = COMMAND_EXEC,
5345                 .jim_handler = jim_target_halt_gdb,
5346                 .help = "used internally for reset processing to halt GDB",
5347         },
5348         {
5349                 .name = "arp_poll",
5350                 .mode = COMMAND_EXEC,
5351                 .jim_handler = jim_target_poll,
5352                 .help = "used internally for reset processing",
5353         },
5354         {
5355                 .name = "arp_reset",
5356                 .mode = COMMAND_EXEC,
5357                 .jim_handler = jim_target_reset,
5358                 .help = "used internally for reset processing",
5359         },
5360         {
5361                 .name = "arp_halt",
5362                 .mode = COMMAND_EXEC,
5363                 .jim_handler = jim_target_halt,
5364                 .help = "used internally for reset processing",
5365         },
5366         {
5367                 .name = "arp_waitstate",
5368                 .mode = COMMAND_EXEC,
5369                 .jim_handler = jim_target_wait_state,
5370                 .help = "used internally for reset processing",
5371         },
5372         {
5373                 .name = "invoke-event",
5374                 .mode = COMMAND_EXEC,
5375                 .jim_handler = jim_target_invoke_event,
5376                 .help = "invoke handler for specified event",
5377                 .usage = "event_name",
5378         },
5379         COMMAND_REGISTRATION_DONE
5380 };
5381
5382 static int target_create(Jim_GetOptInfo *goi)
5383 {
5384         Jim_Obj *new_cmd;
5385         Jim_Cmd *cmd;
5386         const char *cp;
5387         int e;
5388         int x;
5389         struct target *target;
5390         struct command_context *cmd_ctx;
5391
5392         cmd_ctx = current_command_context(goi->interp);
5393         assert(cmd_ctx != NULL);
5394
5395         if (goi->argc < 3) {
5396                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
5397                 return JIM_ERR;
5398         }
5399
5400         /* COMMAND */
5401         Jim_GetOpt_Obj(goi, &new_cmd);
5402         /* does this command exist? */
5403         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
5404         if (cmd) {
5405                 cp = Jim_GetString(new_cmd, NULL);
5406                 Jim_SetResultFormatted(goi->interp, "Command/target: %s Exists", cp);
5407                 return JIM_ERR;
5408         }
5409
5410         /* TYPE */
5411         e = Jim_GetOpt_String(goi, &cp, NULL);
5412         if (e != JIM_OK)
5413                 return e;
5414         struct transport *tr = get_current_transport();
5415         if (tr->override_target) {
5416                 e = tr->override_target(&cp);
5417                 if (e != ERROR_OK) {
5418                         LOG_ERROR("The selected transport doesn't support this target");
5419                         return JIM_ERR;
5420                 }
5421                 LOG_INFO("The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD");
5422         }
5423         /* now does target type exist */
5424         for (x = 0 ; target_types[x] ; x++) {
5425                 if (0 == strcmp(cp, target_types[x]->name)) {
5426                         /* found */
5427                         break;
5428                 }
5429
5430                 /* check for deprecated name */
5431                 if (target_types[x]->deprecated_name) {
5432                         if (0 == strcmp(cp, target_types[x]->deprecated_name)) {
5433                                 /* found */
5434                                 LOG_WARNING("target name is deprecated use: \'%s\'", target_types[x]->name);
5435                                 break;
5436                         }
5437                 }
5438         }
5439         if (target_types[x] == NULL) {
5440                 Jim_SetResultFormatted(goi->interp, "Unknown target type %s, try one of ", cp);
5441                 for (x = 0 ; target_types[x] ; x++) {
5442                         if (target_types[x + 1]) {
5443                                 Jim_AppendStrings(goi->interp,
5444                                                                    Jim_GetResult(goi->interp),
5445                                                                    target_types[x]->name,
5446                                                                    ", ", NULL);
5447                         } else {
5448                                 Jim_AppendStrings(goi->interp,
5449                                                                    Jim_GetResult(goi->interp),
5450                                                                    " or ",
5451                                                                    target_types[x]->name, NULL);
5452                         }
5453                 }
5454                 return JIM_ERR;
5455         }
5456
5457         /* Create it */
5458         target = calloc(1, sizeof(struct target));
5459         /* set target number */
5460         target->target_number = new_target_number();
5461         cmd_ctx->current_target = target;
5462
5463         /* allocate memory for each unique target type */
5464         target->type = calloc(1, sizeof(struct target_type));
5465
5466         memcpy(target->type, target_types[x], sizeof(struct target_type));
5467
5468         /* will be set by "-endian" */
5469         target->endianness = TARGET_ENDIAN_UNKNOWN;
5470
5471         /* default to first core, override with -coreid */
5472         target->coreid = 0;
5473
5474         target->working_area        = 0x0;
5475         target->working_area_size   = 0x0;
5476         target->working_areas       = NULL;
5477         target->backup_working_area = 0;
5478
5479         target->state               = TARGET_UNKNOWN;
5480         target->debug_reason        = DBG_REASON_UNDEFINED;
5481         target->reg_cache           = NULL;
5482         target->breakpoints         = NULL;
5483         target->watchpoints         = NULL;
5484         target->next                = NULL;
5485         target->arch_info           = NULL;
5486
5487         target->verbose_halt_msg        = true;
5488
5489         target->halt_issued                     = false;
5490
5491         /* initialize trace information */
5492         target->trace_info = calloc(1, sizeof(struct trace));
5493
5494         target->dbgmsg          = NULL;
5495         target->dbg_msg_enabled = 0;
5496
5497         target->endianness = TARGET_ENDIAN_UNKNOWN;
5498
5499         target->rtos = NULL;
5500         target->rtos_auto_detect = false;
5501
5502         target->gdb_port_override = NULL;
5503
5504         /* Do the rest as "configure" options */
5505         goi->isconfigure = 1;
5506         e = target_configure(goi, target);
5507
5508         if (e == JIM_OK) {
5509                 if (target->has_dap) {
5510                         if (!target->dap_configured) {
5511                                 Jim_SetResultString(goi->interp, "-dap ?name? required when creating target", -1);
5512                                 e = JIM_ERR;
5513                         }
5514                 } else {
5515                         if (!target->tap_configured) {
5516                                 Jim_SetResultString(goi->interp, "-chain-position ?name? required when creating target", -1);
5517                                 e = JIM_ERR;
5518                         }
5519                 }
5520                 /* tap must be set after target was configured */
5521                 if (target->tap == NULL)
5522                         e = JIM_ERR;
5523         }
5524
5525         if (e != JIM_OK) {
5526                 free(target->gdb_port_override);
5527                 free(target->type);
5528                 free(target);
5529                 return e;
5530         }
5531
5532         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
5533                 /* default endian to little if not specified */
5534                 target->endianness = TARGET_LITTLE_ENDIAN;
5535         }
5536
5537         cp = Jim_GetString(new_cmd, NULL);
5538         target->cmd_name = strdup(cp);
5539
5540         if (target->type->target_create) {
5541                 e = (*(target->type->target_create))(target, goi->interp);
5542                 if (e != ERROR_OK) {
5543                         LOG_DEBUG("target_create failed");
5544                         free(target->gdb_port_override);
5545                         free(target->type);
5546                         free(target->cmd_name);
5547                         free(target);
5548                         return JIM_ERR;
5549                 }
5550         }
5551
5552         /* create the target specific commands */
5553         if (target->type->commands) {
5554                 e = register_commands(cmd_ctx, NULL, target->type->commands);
5555                 if (ERROR_OK != e)
5556                         LOG_ERROR("unable to register '%s' commands", cp);
5557         }
5558
5559         /* append to end of list */
5560         {
5561                 struct target **tpp;
5562                 tpp = &(all_targets);
5563                 while (*tpp)
5564                         tpp = &((*tpp)->next);
5565                 *tpp = target;
5566         }
5567
5568         /* now - create the new target name command */
5569         const struct command_registration target_subcommands[] = {
5570                 {
5571                         .chain = target_instance_command_handlers,
5572                 },
5573                 {
5574                         .chain = target->type->commands,
5575                 },
5576                 COMMAND_REGISTRATION_DONE
5577         };
5578         const struct command_registration target_commands[] = {
5579                 {
5580                         .name = cp,
5581                         .mode = COMMAND_ANY,
5582                         .help = "target command group",
5583                         .usage = "",
5584                         .chain = target_subcommands,
5585                 },
5586                 COMMAND_REGISTRATION_DONE
5587         };
5588         e = register_commands(cmd_ctx, NULL, target_commands);
5589         if (ERROR_OK != e)
5590                 return JIM_ERR;
5591
5592         struct command *c = command_find_in_context(cmd_ctx, cp);
5593         assert(c);
5594         command_set_handler_data(c, target);
5595
5596         return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
5597 }
5598
5599 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5600 {
5601         if (argc != 1) {
5602                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5603                 return JIM_ERR;
5604         }
5605         struct command_context *cmd_ctx = current_command_context(interp);
5606         assert(cmd_ctx != NULL);
5607
5608         Jim_SetResultString(interp, target_name(get_current_target(cmd_ctx)), -1);
5609         return JIM_OK;
5610 }
5611
5612 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5613 {
5614         if (argc != 1) {
5615                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5616                 return JIM_ERR;
5617         }
5618         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5619         for (unsigned x = 0; NULL != target_types[x]; x++) {
5620                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5621                         Jim_NewStringObj(interp, target_types[x]->name, -1));
5622         }
5623         return JIM_OK;
5624 }
5625
5626 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5627 {
5628         if (argc != 1) {
5629                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
5630                 return JIM_ERR;
5631         }
5632         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
5633         struct target *target = all_targets;
5634         while (target) {
5635                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
5636                         Jim_NewStringObj(interp, target_name(target), -1));
5637                 target = target->next;
5638         }
5639         return JIM_OK;
5640 }
5641
5642 static int jim_target_smp(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5643 {
5644         int i;
5645         const char *targetname;
5646         int retval, len;
5647         struct target *target = (struct target *) NULL;
5648         struct target_list *head, *curr, *new;
5649         curr = (struct target_list *) NULL;
5650         head = (struct target_list *) NULL;
5651
5652         retval = 0;
5653         LOG_DEBUG("%d", argc);
5654         /* argv[1] = target to associate in smp
5655          * argv[2] = target to assoicate in smp
5656          * argv[3] ...
5657          */
5658
5659         for (i = 1; i < argc; i++) {
5660
5661                 targetname = Jim_GetString(argv[i], &len);
5662                 target = get_target(targetname);
5663                 LOG_DEBUG("%s ", targetname);
5664                 if (target) {
5665                         new = malloc(sizeof(struct target_list));
5666                         new->target = target;
5667                         new->next = (struct target_list *)NULL;
5668                         if (head == (struct target_list *)NULL) {
5669                                 head = new;
5670                                 curr = head;
5671                         } else {
5672                                 curr->next = new;
5673                                 curr = new;
5674                         }
5675                 }
5676         }
5677         /*  now parse the list of cpu and put the target in smp mode*/
5678         curr = head;
5679
5680         while (curr != (struct target_list *)NULL) {
5681                 target = curr->target;
5682                 target->smp = 1;
5683                 target->head = head;
5684                 curr = curr->next;
5685         }
5686
5687         if (target && target->rtos)
5688                 retval = rtos_smp_init(head->target);
5689
5690         return retval;
5691 }
5692
5693
5694 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
5695 {
5696         Jim_GetOptInfo goi;
5697         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
5698         if (goi.argc < 3) {
5699                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
5700                         "<name> <target_type> [<target_options> ...]");
5701                 return JIM_ERR;
5702         }
5703         return target_create(&goi);
5704 }
5705
5706 static const struct command_registration target_subcommand_handlers[] = {
5707         {
5708                 .name = "init",
5709                 .mode = COMMAND_CONFIG,
5710                 .handler = handle_target_init_command,
5711                 .help = "initialize targets",
5712                 .usage = "",
5713         },
5714         {
5715                 .name = "create",
5716                 .mode = COMMAND_CONFIG,
5717                 .jim_handler = jim_target_create,
5718                 .usage = "name type '-chain-position' name [options ...]",
5719                 .help = "Creates and selects a new target",
5720         },
5721         {
5722                 .name = "current",
5723                 .mode = COMMAND_ANY,
5724                 .jim_handler = jim_target_current,
5725                 .help = "Returns the currently selected target",
5726         },
5727         {
5728                 .name = "types",
5729                 .mode = COMMAND_ANY,
5730                 .jim_handler = jim_target_types,
5731                 .help = "Returns the available target types as "
5732                                 "a list of strings",
5733         },
5734         {
5735                 .name = "names",
5736                 .mode = COMMAND_ANY,
5737                 .jim_handler = jim_target_names,
5738                 .help = "Returns the names of all targets as a list of strings",
5739         },
5740         {
5741                 .name = "smp",
5742                 .mode = COMMAND_ANY,
5743                 .jim_handler = jim_target_smp,
5744                 .usage = "targetname1 targetname2 ...",
5745                 .help = "gather several target in a smp list"
5746         },
5747
5748         COMMAND_REGISTRATION_DONE
5749 };
5750
5751 struct FastLoad {
5752         target_addr_t address;
5753         uint8_t *data;
5754         int length;
5755
5756 };
5757
5758 static int fastload_num;
5759 static struct FastLoad *fastload;
5760
5761 static void free_fastload(void)
5762 {
5763         if (fastload != NULL) {
5764                 int i;
5765                 for (i = 0; i < fastload_num; i++) {
5766                         if (fastload[i].data)
5767                                 free(fastload[i].data);
5768                 }
5769                 free(fastload);
5770                 fastload = NULL;
5771         }
5772 }
5773
5774 COMMAND_HANDLER(handle_fast_load_image_command)
5775 {
5776         uint8_t *buffer;
5777         size_t buf_cnt;
5778         uint32_t image_size;
5779         target_addr_t min_address = 0;
5780         target_addr_t max_address = -1;
5781         int i;
5782
5783         struct image image;
5784
5785         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
5786                         &image, &min_address, &max_address);
5787         if (ERROR_OK != retval)
5788                 return retval;
5789
5790         struct duration bench;
5791         duration_start(&bench);
5792
5793         retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL);
5794         if (retval != ERROR_OK)
5795                 return retval;
5796
5797         image_size = 0x0;
5798         retval = ERROR_OK;
5799         fastload_num = image.num_sections;
5800         fastload = malloc(sizeof(struct FastLoad)*image.num_sections);
5801         if (fastload == NULL) {
5802                 command_print(CMD, "out of memory");
5803                 image_close(&image);
5804                 return ERROR_FAIL;
5805         }
5806         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
5807         for (i = 0; i < image.num_sections; i++) {
5808                 buffer = malloc(image.sections[i].size);
5809                 if (buffer == NULL) {
5810                         command_print(CMD, "error allocating buffer for section (%d bytes)",
5811                                                   (int)(image.sections[i].size));
5812                         retval = ERROR_FAIL;
5813                         break;
5814                 }
5815
5816                 retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt);
5817                 if (retval != ERROR_OK) {
5818                         free(buffer);
5819                         break;
5820                 }
5821
5822                 uint32_t offset = 0;
5823                 uint32_t length = buf_cnt;
5824
5825                 /* DANGER!!! beware of unsigned comparision here!!! */
5826
5827                 if ((image.sections[i].base_address + buf_cnt >= min_address) &&
5828                                 (image.sections[i].base_address < max_address)) {
5829                         if (image.sections[i].base_address < min_address) {
5830                                 /* clip addresses below */
5831                                 offset += min_address-image.sections[i].base_address;
5832                                 length -= offset;
5833                         }
5834
5835                         if (image.sections[i].base_address + buf_cnt > max_address)
5836                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
5837
5838                         fastload[i].address = image.sections[i].base_address + offset;
5839                         fastload[i].data = malloc(length);
5840                         if (fastload[i].data == NULL) {
5841                                 free(buffer);
5842                                 command_print(CMD, "error allocating buffer for section (%" PRIu32 " bytes)",
5843                                                           length);
5844                                 retval = ERROR_FAIL;
5845                                 break;
5846                         }
5847                         memcpy(fastload[i].data, buffer + offset, length);
5848                         fastload[i].length = length;
5849
5850                         image_size += length;
5851                         command_print(CMD, "%u bytes written at address 0x%8.8x",
5852                                                   (unsigned int)length,
5853                                                   ((unsigned int)(image.sections[i].base_address + offset)));
5854                 }
5855
5856                 free(buffer);
5857         }
5858
5859         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
5860                 command_print(CMD, "Loaded %" PRIu32 " bytes "
5861                                 "in %fs (%0.3f KiB/s)", image_size,
5862                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
5863
5864                 command_print(CMD,
5865                                 "WARNING: image has not been loaded to target!"
5866                                 "You can issue a 'fast_load' to finish loading.");
5867         }
5868
5869         image_close(&image);
5870
5871         if (retval != ERROR_OK)
5872                 free_fastload();
5873
5874         return retval;
5875 }
5876
5877 COMMAND_HANDLER(handle_fast_load_command)
5878 {
5879         if (CMD_ARGC > 0)
5880                 return ERROR_COMMAND_SYNTAX_ERROR;
5881         if (fastload == NULL) {
5882                 LOG_ERROR("No image in memory");
5883                 return ERROR_FAIL;
5884         }
5885         int i;
5886         int64_t ms = timeval_ms();
5887         int size = 0;
5888         int retval = ERROR_OK;
5889         for (i = 0; i < fastload_num; i++) {
5890                 struct target *target = get_current_target(CMD_CTX);
5891                 command_print(CMD, "Write to 0x%08x, length 0x%08x",
5892                                           (unsigned int)(fastload[i].address),
5893                                           (unsigned int)(fastload[i].length));
5894                 retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
5895                 if (retval != ERROR_OK)
5896                         break;
5897                 size += fastload[i].length;
5898         }
5899         if (retval == ERROR_OK) {
5900                 int64_t after = timeval_ms();
5901                 command_print(CMD, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
5902         }
5903         return retval;
5904 }
5905
5906 static const struct command_registration target_command_handlers[] = {
5907         {
5908                 .name = "targets",
5909                 .handler = handle_targets_command,
5910                 .mode = COMMAND_ANY,
5911                 .help = "change current default target (one parameter) "
5912                         "or prints table of all targets (no parameters)",
5913                 .usage = "[target]",
5914         },
5915         {
5916                 .name = "target",
5917                 .mode = COMMAND_CONFIG,
5918                 .help = "configure target",
5919                 .chain = target_subcommand_handlers,
5920                 .usage = "",
5921         },
5922         COMMAND_REGISTRATION_DONE
5923 };
5924
5925 int target_register_commands(struct command_context *cmd_ctx)
5926 {
5927         return register_commands(cmd_ctx, NULL, target_command_handlers);
5928 }
5929
5930 static bool target_reset_nag = true;
5931
5932 bool get_target_reset_nag(void)
5933 {
5934         return target_reset_nag;
5935 }
5936
5937 COMMAND_HANDLER(handle_target_reset_nag)
5938 {
5939         return CALL_COMMAND_HANDLER(handle_command_parse_bool,
5940                         &target_reset_nag, "Nag after each reset about options to improve "
5941                         "performance");
5942 }
5943
5944 COMMAND_HANDLER(handle_ps_command)
5945 {
5946         struct target *target = get_current_target(CMD_CTX);
5947         char *display;
5948         if (target->state != TARGET_HALTED) {
5949                 LOG_INFO("target not halted !!");
5950                 return ERROR_OK;
5951         }
5952
5953         if ((target->rtos) && (target->rtos->type)
5954                         && (target->rtos->type->ps_command)) {
5955                 display = target->rtos->type->ps_command(target);
5956                 command_print(CMD, "%s", display);
5957                 free(display);
5958                 return ERROR_OK;
5959         } else {
5960                 LOG_INFO("failed");
5961                 return ERROR_TARGET_FAILURE;
5962         }
5963 }
5964
5965 static void binprint(struct command_invocation *cmd, const char *text, const uint8_t *buf, int size)
5966 {
5967         if (text != NULL)
5968                 command_print_sameline(cmd, "%s", text);
5969         for (int i = 0; i < size; i++)
5970                 command_print_sameline(cmd, " %02x", buf[i]);
5971         command_print(cmd, " ");
5972 }
5973
5974 COMMAND_HANDLER(handle_test_mem_access_command)
5975 {
5976         struct target *target = get_current_target(CMD_CTX);
5977         uint32_t test_size;
5978         int retval = ERROR_OK;
5979
5980         if (target->state != TARGET_HALTED) {
5981                 LOG_INFO("target not halted !!");
5982                 return ERROR_FAIL;
5983         }
5984
5985         if (CMD_ARGC != 1)
5986                 return ERROR_COMMAND_SYNTAX_ERROR;
5987
5988         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], test_size);
5989
5990         /* Test reads */
5991         size_t num_bytes = test_size + 4;
5992
5993         struct working_area *wa = NULL;
5994         retval = target_alloc_working_area(target, num_bytes, &wa);
5995         if (retval != ERROR_OK) {
5996                 LOG_ERROR("Not enough working area");
5997                 return ERROR_FAIL;
5998         }
5999
6000         uint8_t *test_pattern = malloc(num_bytes);
6001
6002         for (size_t i = 0; i < num_bytes; i++)
6003                 test_pattern[i] = rand();
6004
6005         retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6006         if (retval != ERROR_OK) {
6007                 LOG_ERROR("Test pattern write failed");
6008                 goto out;
6009         }
6010
6011         for (int host_offset = 0; host_offset <= 1; host_offset++) {
6012                 for (int size = 1; size <= 4; size *= 2) {
6013                         for (int offset = 0; offset < 4; offset++) {
6014                                 uint32_t count = test_size / size;
6015                                 size_t host_bufsiz = (count + 2) * size + host_offset;
6016                                 uint8_t *read_ref = malloc(host_bufsiz);
6017                                 uint8_t *read_buf = malloc(host_bufsiz);
6018
6019                                 for (size_t i = 0; i < host_bufsiz; i++) {
6020                                         read_ref[i] = rand();
6021                                         read_buf[i] = read_ref[i];
6022                                 }
6023                                 command_print_sameline(CMD,
6024                                                 "Test read %" PRIu32 " x %d @ %d to %saligned buffer: ", count,
6025                                                 size, offset, host_offset ? "un" : "");
6026
6027                                 struct duration bench;
6028                                 duration_start(&bench);
6029
6030                                 retval = target_read_memory(target, wa->address + offset, size, count,
6031                                                 read_buf + size + host_offset);
6032
6033                                 duration_measure(&bench);
6034
6035                                 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6036                                         command_print(CMD, "Unsupported alignment");
6037                                         goto next;
6038                                 } else if (retval != ERROR_OK) {
6039                                         command_print(CMD, "Memory read failed");
6040                                         goto next;
6041                                 }
6042
6043                                 /* replay on host */
6044                                 memcpy(read_ref + size + host_offset, test_pattern + offset, count * size);
6045
6046                                 /* check result */
6047                                 int result = memcmp(read_ref, read_buf, host_bufsiz);
6048                                 if (result == 0) {
6049                                         command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6050                                                         duration_elapsed(&bench),
6051                                                         duration_kbps(&bench, count * size));
6052                                 } else {
6053                                         command_print(CMD, "Compare failed");
6054                                         binprint(CMD, "ref:", read_ref, host_bufsiz);
6055                                         binprint(CMD, "buf:", read_buf, host_bufsiz);
6056                                 }
6057 next:
6058                                 free(read_ref);
6059                                 free(read_buf);
6060                         }
6061                 }
6062         }
6063
6064 out:
6065         free(test_pattern);
6066
6067         if (wa != NULL)
6068                 target_free_working_area(target, wa);
6069
6070         /* Test writes */
6071         num_bytes = test_size + 4 + 4 + 4;
6072
6073         retval = target_alloc_working_area(target, num_bytes, &wa);
6074         if (retval != ERROR_OK) {
6075                 LOG_ERROR("Not enough working area");
6076                 return ERROR_FAIL;
6077         }
6078
6079         test_pattern = malloc(num_bytes);
6080
6081         for (size_t i = 0; i < num_bytes; i++)
6082                 test_pattern[i] = rand();
6083
6084         for (int host_offset = 0; host_offset <= 1; host_offset++) {
6085                 for (int size = 1; size <= 4; size *= 2) {
6086                         for (int offset = 0; offset < 4; offset++) {
6087                                 uint32_t count = test_size / size;
6088                                 size_t host_bufsiz = count * size + host_offset;
6089                                 uint8_t *read_ref = malloc(num_bytes);
6090                                 uint8_t *read_buf = malloc(num_bytes);
6091                                 uint8_t *write_buf = malloc(host_bufsiz);
6092
6093                                 for (size_t i = 0; i < host_bufsiz; i++)
6094                                         write_buf[i] = rand();
6095                                 command_print_sameline(CMD,
6096                                                 "Test write %" PRIu32 " x %d @ %d from %saligned buffer: ", count,
6097                                                 size, offset, host_offset ? "un" : "");
6098
6099                                 retval = target_write_memory(target, wa->address, 1, num_bytes, test_pattern);
6100                                 if (retval != ERROR_OK) {
6101                                         command_print(CMD, "Test pattern write failed");
6102                                         goto nextw;
6103                                 }
6104
6105                                 /* replay on host */
6106                                 memcpy(read_ref, test_pattern, num_bytes);
6107                                 memcpy(read_ref + size + offset, write_buf + host_offset, count * size);
6108
6109                                 struct duration bench;
6110                                 duration_start(&bench);
6111
6112                                 retval = target_write_memory(target, wa->address + size + offset, size, count,
6113                                                 write_buf + host_offset);
6114
6115                                 duration_measure(&bench);
6116
6117                                 if (retval == ERROR_TARGET_UNALIGNED_ACCESS) {
6118                                         command_print(CMD, "Unsupported alignment");
6119                                         goto nextw;
6120                                 } else if (retval != ERROR_OK) {
6121                                         command_print(CMD, "Memory write failed");
6122                                         goto nextw;
6123                                 }
6124
6125                                 /* read back */
6126                                 retval = target_read_memory(target, wa->address, 1, num_bytes, read_buf);
6127                                 if (retval != ERROR_OK) {
6128                                         command_print(CMD, "Test pattern write failed");
6129                                         goto nextw;
6130                                 }
6131
6132                                 /* check result */
6133                                 int result = memcmp(read_ref, read_buf, num_bytes);
6134                                 if (result == 0) {
6135                                         command_print(CMD, "Pass in %fs (%0.3f KiB/s)",
6136                                                         duration_elapsed(&bench),
6137                                                         duration_kbps(&bench, count * size));
6138                                 } else {
6139                                         command_print(CMD, "Compare failed");
6140                                         binprint(CMD, "ref:", read_ref, num_bytes);
6141                                         binprint(CMD, "buf:", read_buf, num_bytes);
6142                                 }
6143 nextw:
6144                                 free(read_ref);
6145                                 free(read_buf);
6146                         }
6147                 }
6148         }
6149
6150         free(test_pattern);
6151
6152         if (wa != NULL)
6153                 target_free_working_area(target, wa);
6154         return retval;
6155 }
6156
6157 static const struct command_registration target_exec_command_handlers[] = {
6158         {
6159                 .name = "fast_load_image",
6160                 .handler = handle_fast_load_image_command,
6161                 .mode = COMMAND_ANY,
6162                 .help = "Load image into server memory for later use by "
6163                         "fast_load; primarily for profiling",
6164                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6165                         "[min_address [max_length]]",
6166         },
6167         {
6168                 .name = "fast_load",
6169                 .handler = handle_fast_load_command,
6170                 .mode = COMMAND_EXEC,
6171                 .help = "loads active fast load image to current target "
6172                         "- mainly for profiling purposes",
6173                 .usage = "",
6174         },
6175         {
6176                 .name = "profile",
6177                 .handler = handle_profile_command,
6178                 .mode = COMMAND_EXEC,
6179                 .usage = "seconds filename [start end]",
6180                 .help = "profiling samples the CPU PC",
6181         },
6182         /** @todo don't register virt2phys() unless target supports it */
6183         {
6184                 .name = "virt2phys",
6185                 .handler = handle_virt2phys_command,
6186                 .mode = COMMAND_ANY,
6187                 .help = "translate a virtual address into a physical address",
6188                 .usage = "virtual_address",
6189         },
6190         {
6191                 .name = "reg",
6192                 .handler = handle_reg_command,
6193                 .mode = COMMAND_EXEC,
6194                 .help = "display (reread from target with \"force\") or set a register; "
6195                         "with no arguments, displays all registers and their values",
6196                 .usage = "[(register_number|register_name) [(value|'force')]]",
6197         },
6198         {
6199                 .name = "poll",
6200                 .handler = handle_poll_command,
6201                 .mode = COMMAND_EXEC,
6202                 .help = "poll target state; or reconfigure background polling",
6203                 .usage = "['on'|'off']",
6204         },
6205         {
6206                 .name = "wait_halt",
6207                 .handler = handle_wait_halt_command,
6208                 .mode = COMMAND_EXEC,
6209                 .help = "wait up to the specified number of milliseconds "
6210                         "(default 5000) for a previously requested halt",
6211                 .usage = "[milliseconds]",
6212         },
6213         {
6214                 .name = "halt",
6215                 .handler = handle_halt_command,
6216                 .mode = COMMAND_EXEC,
6217                 .help = "request target to halt, then wait up to the specified"
6218                         "number of milliseconds (default 5000) for it to complete",
6219                 .usage = "[milliseconds]",
6220         },
6221         {
6222                 .name = "resume",
6223                 .handler = handle_resume_command,
6224                 .mode = COMMAND_EXEC,
6225                 .help = "resume target execution from current PC or address",
6226                 .usage = "[address]",
6227         },
6228         {
6229                 .name = "reset",
6230                 .handler = handle_reset_command,
6231                 .mode = COMMAND_EXEC,
6232                 .usage = "[run|halt|init]",
6233                 .help = "Reset all targets into the specified mode."
6234                         "Default reset mode is run, if not given.",
6235         },
6236         {
6237                 .name = "soft_reset_halt",
6238                 .handler = handle_soft_reset_halt_command,
6239                 .mode = COMMAND_EXEC,
6240                 .usage = "",
6241                 .help = "halt the target and do a soft reset",
6242         },
6243         {
6244                 .name = "step",
6245                 .handler = handle_step_command,
6246                 .mode = COMMAND_EXEC,
6247                 .help = "step one instruction from current PC or address",
6248                 .usage = "[address]",
6249         },
6250         {
6251                 .name = "mdd",
6252                 .handler = handle_md_command,
6253                 .mode = COMMAND_EXEC,
6254                 .help = "display memory double-words",
6255                 .usage = "['phys'] address [count]",
6256         },
6257         {
6258                 .name = "mdw",
6259                 .handler = handle_md_command,
6260                 .mode = COMMAND_EXEC,
6261                 .help = "display memory words",
6262                 .usage = "['phys'] address [count]",
6263         },
6264         {
6265                 .name = "mdh",
6266                 .handler = handle_md_command,
6267                 .mode = COMMAND_EXEC,
6268                 .help = "display memory half-words",
6269                 .usage = "['phys'] address [count]",
6270         },
6271         {
6272                 .name = "mdb",
6273                 .handler = handle_md_command,
6274                 .mode = COMMAND_EXEC,
6275                 .help = "display memory bytes",
6276                 .usage = "['phys'] address [count]",
6277         },
6278         {
6279                 .name = "mwd",
6280                 .handler = handle_mw_command,
6281                 .mode = COMMAND_EXEC,
6282                 .help = "write memory double-word",
6283                 .usage = "['phys'] address value [count]",
6284         },
6285         {
6286                 .name = "mww",
6287                 .handler = handle_mw_command,
6288                 .mode = COMMAND_EXEC,
6289                 .help = "write memory word",
6290                 .usage = "['phys'] address value [count]",
6291         },
6292         {
6293                 .name = "mwh",
6294                 .handler = handle_mw_command,
6295                 .mode = COMMAND_EXEC,
6296                 .help = "write memory half-word",
6297                 .usage = "['phys'] address value [count]",
6298         },
6299         {
6300                 .name = "mwb",
6301                 .handler = handle_mw_command,
6302                 .mode = COMMAND_EXEC,
6303                 .help = "write memory byte",
6304                 .usage = "['phys'] address value [count]",
6305         },
6306         {
6307                 .name = "bp",
6308                 .handler = handle_bp_command,
6309                 .mode = COMMAND_EXEC,
6310                 .help = "list or set hardware or software breakpoint",
6311                 .usage = "[<address> [<asid>] <length> ['hw'|'hw_ctx']]",
6312         },
6313         {
6314                 .name = "rbp",
6315                 .handler = handle_rbp_command,
6316                 .mode = COMMAND_EXEC,
6317                 .help = "remove breakpoint",
6318                 .usage = "address",
6319         },
6320         {
6321                 .name = "wp",
6322                 .handler = handle_wp_command,
6323                 .mode = COMMAND_EXEC,
6324                 .help = "list (no params) or create watchpoints",
6325                 .usage = "[address length [('r'|'w'|'a') value [mask]]]",
6326         },
6327         {
6328                 .name = "rwp",
6329                 .handler = handle_rwp_command,
6330                 .mode = COMMAND_EXEC,
6331                 .help = "remove watchpoint",
6332                 .usage = "address",
6333         },
6334         {
6335                 .name = "load_image",
6336                 .handler = handle_load_image_command,
6337                 .mode = COMMAND_EXEC,
6338                 .usage = "filename address ['bin'|'ihex'|'elf'|'s19'] "
6339                         "[min_address] [max_length]",
6340         },
6341         {
6342                 .name = "dump_image",
6343                 .handler = handle_dump_image_command,
6344                 .mode = COMMAND_EXEC,
6345                 .usage = "filename address size",
6346         },
6347         {
6348                 .name = "verify_image_checksum",
6349                 .handler = handle_verify_image_checksum_command,
6350                 .mode = COMMAND_EXEC,
6351                 .usage = "filename [offset [type]]",
6352         },
6353         {
6354                 .name = "verify_image",
6355                 .handler = handle_verify_image_command,
6356                 .mode = COMMAND_EXEC,
6357                 .usage = "filename [offset [type]]",
6358         },
6359         {
6360                 .name = "test_image",
6361                 .handler = handle_test_image_command,
6362                 .mode = COMMAND_EXEC,
6363                 .usage = "filename [offset [type]]",
6364         },
6365         {
6366                 .name = "mem2array",
6367                 .mode = COMMAND_EXEC,
6368                 .jim_handler = jim_mem2array,
6369                 .help = "read 8/16/32 bit memory and return as a TCL array "
6370                         "for script processing",
6371                 .usage = "arrayname bitwidth address count",
6372         },
6373         {
6374                 .name = "array2mem",
6375                 .mode = COMMAND_EXEC,
6376                 .jim_handler = jim_array2mem,
6377                 .help = "convert a TCL array to memory locations "
6378                         "and write the 8/16/32 bit values",
6379                 .usage = "arrayname bitwidth address count",
6380         },
6381         {
6382                 .name = "reset_nag",
6383                 .handler = handle_target_reset_nag,
6384                 .mode = COMMAND_ANY,
6385                 .help = "Nag after each reset about options that could have been "
6386                                 "enabled to improve performance. ",
6387                 .usage = "['enable'|'disable']",
6388         },
6389         {
6390                 .name = "ps",
6391                 .handler = handle_ps_command,
6392                 .mode = COMMAND_EXEC,
6393                 .help = "list all tasks ",
6394                 .usage = " ",
6395         },
6396         {
6397                 .name = "test_mem_access",
6398                 .handler = handle_test_mem_access_command,
6399                 .mode = COMMAND_EXEC,
6400                 .help = "Test the target's memory access functions",
6401                 .usage = "size",
6402         },
6403
6404         COMMAND_REGISTRATION_DONE
6405 };
6406 static int target_register_user_commands(struct command_context *cmd_ctx)
6407 {
6408         int retval = ERROR_OK;
6409         retval = target_request_register_commands(cmd_ctx);
6410         if (retval != ERROR_OK)
6411                 return retval;
6412
6413         retval = trace_register_commands(cmd_ctx);
6414         if (retval != ERROR_OK)
6415                 return retval;
6416
6417
6418         return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
6419 }