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