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