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