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