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