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