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