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