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