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