target: "mcr" and "mrc" are ARM-specific
[fw/openocd] / src / target / target.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007-2009 Ã˜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  *   This program is free software; you can redistribute it and/or modify  *
18  *   it under the terms of the GNU General Public License as published by  *
19  *   the Free Software Foundation; either version 2 of the License, or     *
20  *   (at your option) any later version.                                   *
21  *                                                                         *
22  *   This program is distributed in the hope that it will be useful,       *
23  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
24  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
25  *   GNU General Public License for more details.                          *
26  *                                                                         *
27  *   You should have received a copy of the GNU General Public License     *
28  *   along with this program; if not, write to the                         *
29  *   Free Software Foundation, Inc.,                                       *
30  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
31  ***************************************************************************/
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
35
36 #include "target.h"
37 #include "target_type.h"
38 #include "target_request.h"
39 #include "breakpoints.h"
40 #include "time_support.h"
41 #include "register.h"
42 #include "trace.h"
43 #include "image.h"
44 #include "jtag.h"
45
46
47 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv);
48 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv);
49
50 /* targets */
51 extern struct target_type arm7tdmi_target;
52 extern struct target_type arm720t_target;
53 extern struct target_type arm9tdmi_target;
54 extern struct target_type arm920t_target;
55 extern struct target_type arm966e_target;
56 extern struct target_type arm926ejs_target;
57 extern struct target_type fa526_target;
58 extern struct target_type feroceon_target;
59 extern struct target_type dragonite_target;
60 extern struct target_type xscale_target;
61 extern struct target_type cortexm3_target;
62 extern struct target_type cortexa8_target;
63 extern struct target_type arm11_target;
64 extern struct target_type mips_m4k_target;
65 extern struct target_type avr_target;
66 extern struct target_type testee_target;
67
68 struct target_type *target_types[] =
69 {
70         &arm7tdmi_target,
71         &arm9tdmi_target,
72         &arm920t_target,
73         &arm720t_target,
74         &arm966e_target,
75         &arm926ejs_target,
76         &fa526_target,
77         &feroceon_target,
78         &dragonite_target,
79         &xscale_target,
80         &cortexm3_target,
81         &cortexa8_target,
82         &arm11_target,
83         &mips_m4k_target,
84         &avr_target,
85         &testee_target,
86         NULL,
87 };
88
89 struct target *all_targets = NULL;
90 struct target_event_callback *target_event_callbacks = NULL;
91 struct target_timer_callback *target_timer_callbacks = NULL;
92
93 const Jim_Nvp nvp_assert[] = {
94         { .name = "assert", NVP_ASSERT },
95         { .name = "deassert", NVP_DEASSERT },
96         { .name = "T", NVP_ASSERT },
97         { .name = "F", NVP_DEASSERT },
98         { .name = "t", NVP_ASSERT },
99         { .name = "f", NVP_DEASSERT },
100         { .name = NULL, .value = -1 }
101 };
102
103 const Jim_Nvp nvp_error_target[] = {
104         { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
105         { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
106         { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
107         { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
108         { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
109         { .value = ERROR_TARGET_UNALIGNED_ACCESS   , .name = "err-unaligned-access" },
110         { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
111         { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
112         { .value = ERROR_TARGET_TRANSLATION_FAULT  , .name = "err-translation-fault" },
113         { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
114         { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
115         { .value = -1, .name = NULL }
116 };
117
118 const char *target_strerror_safe(int err)
119 {
120         const Jim_Nvp *n;
121
122         n = Jim_Nvp_value2name_simple(nvp_error_target, err);
123         if (n->name == NULL) {
124                 return "unknown";
125         } else {
126                 return n->name;
127         }
128 }
129
130 static const Jim_Nvp nvp_target_event[] = {
131         { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
132         { .value = TARGET_EVENT_OLD_pre_resume         , .name = "old-pre_resume" },
133
134         { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
135         { .value = TARGET_EVENT_HALTED, .name = "halted" },
136         { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
137         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
138         { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
139
140         { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
141         { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
142
143         /* historical name */
144
145         { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
146
147         { .value = TARGET_EVENT_RESET_ASSERT_PRE,    .name = "reset-assert-pre" },
148         { .value = TARGET_EVENT_RESET_ASSERT,        .name = "reset-assert" },
149         { .value = TARGET_EVENT_RESET_ASSERT_POST,   .name = "reset-assert-post" },
150         { .value = TARGET_EVENT_RESET_DEASSERT_PRE,  .name = "reset-deassert-pre" },
151         { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
152         { .value = TARGET_EVENT_RESET_HALT_PRE,      .name = "reset-halt-pre" },
153         { .value = TARGET_EVENT_RESET_HALT_POST,     .name = "reset-halt-post" },
154         { .value = TARGET_EVENT_RESET_WAIT_PRE,      .name = "reset-wait-pre" },
155         { .value = TARGET_EVENT_RESET_WAIT_POST,     .name = "reset-wait-post" },
156         { .value = TARGET_EVENT_RESET_INIT,          .name = "reset-init" },
157         { .value = TARGET_EVENT_RESET_END,           .name = "reset-end" },
158
159         { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
160         { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
161
162         { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
163         { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
164
165         { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
166         { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
167
168         { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
169         { .value = TARGET_EVENT_GDB_FLASH_WRITE_END  , .name = "gdb-flash-write-end"   },
170
171         { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
172         { .value = TARGET_EVENT_GDB_FLASH_ERASE_END  , .name = "gdb-flash-erase-end" },
173
174         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
175         { .value = TARGET_EVENT_RESUMED     , .name = "resume-ok" },
176         { .value = TARGET_EVENT_RESUME_END  , .name = "resume-end" },
177
178         { .name = NULL, .value = -1 }
179 };
180
181 const Jim_Nvp nvp_target_state[] = {
182         { .name = "unknown", .value = TARGET_UNKNOWN },
183         { .name = "running", .value = TARGET_RUNNING },
184         { .name = "halted",  .value = TARGET_HALTED },
185         { .name = "reset",   .value = TARGET_RESET },
186         { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
187         { .name = NULL, .value = -1 },
188 };
189
190 const Jim_Nvp nvp_target_debug_reason [] = {
191         { .name = "debug-request"            , .value = DBG_REASON_DBGRQ },
192         { .name = "breakpoint"               , .value = DBG_REASON_BREAKPOINT },
193         { .name = "watchpoint"               , .value = DBG_REASON_WATCHPOINT },
194         { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
195         { .name = "single-step"              , .value = DBG_REASON_SINGLESTEP },
196         { .name = "target-not-halted"        , .value = DBG_REASON_NOTHALTED  },
197         { .name = "undefined"                , .value = DBG_REASON_UNDEFINED },
198         { .name = NULL, .value = -1 },
199 };
200
201 const Jim_Nvp nvp_target_endian[] = {
202         { .name = "big",    .value = TARGET_BIG_ENDIAN },
203         { .name = "little", .value = TARGET_LITTLE_ENDIAN },
204         { .name = "be",     .value = TARGET_BIG_ENDIAN },
205         { .name = "le",     .value = TARGET_LITTLE_ENDIAN },
206         { .name = NULL,     .value = -1 },
207 };
208
209 const Jim_Nvp nvp_reset_modes[] = {
210         { .name = "unknown", .value = RESET_UNKNOWN },
211         { .name = "run"    , .value = RESET_RUN },
212         { .name = "halt"   , .value = RESET_HALT },
213         { .name = "init"   , .value = RESET_INIT },
214         { .name = NULL     , .value = -1 },
215 };
216
217 const char *
218 target_state_name( struct target *t )
219 {
220         const char *cp;
221         cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
222         if( !cp ){
223                 LOG_ERROR("Invalid target state: %d", (int)(t->state));
224                 cp = "(*BUG*unknown*BUG*)";
225         }
226         return cp;
227 }
228
229 /* determine the number of the new target */
230 static int new_target_number(void)
231 {
232         struct target *t;
233         int x;
234
235         /* number is 0 based */
236         x = -1;
237         t = all_targets;
238         while (t) {
239                 if (x < t->target_number) {
240                         x = t->target_number;
241                 }
242                 t = t->next;
243         }
244         return x + 1;
245 }
246
247 /* read a uint32_t from a buffer in target memory endianness */
248 uint32_t target_buffer_get_u32(struct target *target, const uint8_t *buffer)
249 {
250         if (target->endianness == TARGET_LITTLE_ENDIAN)
251                 return le_to_h_u32(buffer);
252         else
253                 return be_to_h_u32(buffer);
254 }
255
256 /* read a uint16_t from a buffer in target memory endianness */
257 uint16_t target_buffer_get_u16(struct target *target, const uint8_t *buffer)
258 {
259         if (target->endianness == TARGET_LITTLE_ENDIAN)
260                 return le_to_h_u16(buffer);
261         else
262                 return be_to_h_u16(buffer);
263 }
264
265 /* read a uint8_t from a buffer in target memory endianness */
266 uint8_t target_buffer_get_u8(struct target *target, const uint8_t *buffer)
267 {
268         return *buffer & 0x0ff;
269 }
270
271 /* write a uint32_t to a buffer in target memory endianness */
272 void target_buffer_set_u32(struct target *target, uint8_t *buffer, uint32_t value)
273 {
274         if (target->endianness == TARGET_LITTLE_ENDIAN)
275                 h_u32_to_le(buffer, value);
276         else
277                 h_u32_to_be(buffer, value);
278 }
279
280 /* write a uint16_t to a buffer in target memory endianness */
281 void target_buffer_set_u16(struct target *target, uint8_t *buffer, uint16_t value)
282 {
283         if (target->endianness == TARGET_LITTLE_ENDIAN)
284                 h_u16_to_le(buffer, value);
285         else
286                 h_u16_to_be(buffer, value);
287 }
288
289 /* write a uint8_t to a buffer in target memory endianness */
290 void target_buffer_set_u8(struct target *target, uint8_t *buffer, uint8_t value)
291 {
292         *buffer = value;
293 }
294
295 /* return a pointer to a configured target; id is name or number */
296 struct target *get_target(const char *id)
297 {
298         struct target *target;
299
300         /* try as tcltarget name */
301         for (target = all_targets; target; target = target->next) {
302                 if (target->cmd_name == NULL)
303                         continue;
304                 if (strcmp(id, target->cmd_name) == 0)
305                         return target;
306         }
307
308         /* It's OK to remove this fallback sometime after August 2010 or so */
309
310         /* no match, try as number */
311         unsigned num;
312         if (parse_uint(id, &num) != ERROR_OK)
313                 return NULL;
314
315         for (target = all_targets; target; target = target->next) {
316                 if (target->target_number == (int)num) {
317                         LOG_WARNING("use '%s' as target identifier, not '%u'",
318                                         target->cmd_name, num);
319                         return target;
320                 }
321         }
322
323         return NULL;
324 }
325
326 /* returns a pointer to the n-th configured target */
327 static struct target *get_target_by_num(int num)
328 {
329         struct target *target = all_targets;
330
331         while (target) {
332                 if (target->target_number == num) {
333                         return target;
334                 }
335                 target = target->next;
336         }
337
338         return NULL;
339 }
340
341 struct target* get_current_target(struct command_context *cmd_ctx)
342 {
343         struct target *target = get_target_by_num(cmd_ctx->current_target);
344
345         if (target == NULL)
346         {
347                 LOG_ERROR("BUG: current_target out of bounds");
348                 exit(-1);
349         }
350
351         return target;
352 }
353
354 int target_poll(struct target *target)
355 {
356         int retval;
357
358         /* We can't poll until after examine */
359         if (!target_was_examined(target))
360         {
361                 /* Fail silently lest we pollute the log */
362                 return ERROR_FAIL;
363         }
364
365         retval = target->type->poll(target);
366         if (retval != ERROR_OK)
367                 return retval;
368
369         if (target->halt_issued)
370         {
371                 if (target->state == TARGET_HALTED)
372                 {
373                         target->halt_issued = false;
374                 } else
375                 {
376                         long long t = timeval_ms() - target->halt_issued_time;
377                         if (t>1000)
378                         {
379                                 target->halt_issued = false;
380                                 LOG_INFO("Halt timed out, wake up GDB.");
381                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
382                         }
383                 }
384         }
385
386         return ERROR_OK;
387 }
388
389 int target_halt(struct target *target)
390 {
391         int retval;
392         /* We can't poll until after examine */
393         if (!target_was_examined(target))
394         {
395                 LOG_ERROR("Target not examined yet");
396                 return ERROR_FAIL;
397         }
398
399         retval = target->type->halt(target);
400         if (retval != ERROR_OK)
401                 return retval;
402
403         target->halt_issued = true;
404         target->halt_issued_time = timeval_ms();
405
406         return ERROR_OK;
407 }
408
409 int target_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
410 {
411         int retval;
412
413         /* We can't poll until after examine */
414         if (!target_was_examined(target))
415         {
416                 LOG_ERROR("Target not examined yet");
417                 return ERROR_FAIL;
418         }
419
420         /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
421          * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
422          * the application.
423          */
424         if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
425                 return retval;
426
427         return retval;
428 }
429
430 int target_process_reset(struct command_context *cmd_ctx, enum target_reset_mode reset_mode)
431 {
432         char buf[100];
433         int retval;
434         Jim_Nvp *n;
435         n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
436         if (n->name == NULL) {
437                 LOG_ERROR("invalid reset mode");
438                 return ERROR_FAIL;
439         }
440
441         /* disable polling during reset to make reset event scripts
442          * more predictable, i.e. dr/irscan & pathmove in events will
443          * not have JTAG operations injected into the middle of a sequence.
444          */
445         bool save_poll = jtag_poll_get_enabled();
446
447         jtag_poll_set_enabled(false);
448
449         sprintf(buf, "ocd_process_reset %s", n->name);
450         retval = Jim_Eval(cmd_ctx->interp, buf);
451
452         jtag_poll_set_enabled(save_poll);
453
454         if (retval != JIM_OK) {
455                 Jim_PrintErrorMessage(cmd_ctx->interp);
456                 return ERROR_FAIL;
457         }
458
459         /* We want any events to be processed before the prompt */
460         retval = target_call_timer_callbacks_now();
461
462         return retval;
463 }
464
465 static int identity_virt2phys(struct target *target,
466                 uint32_t virtual, uint32_t *physical)
467 {
468         *physical = virtual;
469         return ERROR_OK;
470 }
471
472 static int no_mmu(struct target *target, int *enabled)
473 {
474         *enabled = 0;
475         return ERROR_OK;
476 }
477
478 static int default_examine(struct target *target)
479 {
480         target_set_examined(target);
481         return ERROR_OK;
482 }
483
484 int target_examine_one(struct target *target)
485 {
486         return target->type->examine(target);
487 }
488
489 static int jtag_enable_callback(enum jtag_event event, void *priv)
490 {
491         struct target *target = priv;
492
493         if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
494                 return ERROR_OK;
495
496         jtag_unregister_event_callback(jtag_enable_callback, target);
497         return target_examine_one(target);
498 }
499
500
501 /* Targets that correctly implement init + examine, i.e.
502  * no communication with target during init:
503  *
504  * XScale
505  */
506 int target_examine(void)
507 {
508         int retval = ERROR_OK;
509         struct target *target;
510
511         for (target = all_targets; target; target = target->next)
512         {
513                 /* defer examination, but don't skip it */
514                 if (!target->tap->enabled) {
515                         jtag_register_event_callback(jtag_enable_callback,
516                                         target);
517                         continue;
518                 }
519                 if ((retval = target_examine_one(target)) != ERROR_OK)
520                         return retval;
521         }
522         return retval;
523 }
524 const char *target_type_name(struct target *target)
525 {
526         return target->type->name;
527 }
528
529 static int target_write_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
530 {
531         if (!target_was_examined(target))
532         {
533                 LOG_ERROR("Target not examined yet");
534                 return ERROR_FAIL;
535         }
536         return target->type->write_memory_imp(target, address, size, count, buffer);
537 }
538
539 static int target_read_memory_imp(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
540 {
541         if (!target_was_examined(target))
542         {
543                 LOG_ERROR("Target not examined yet");
544                 return ERROR_FAIL;
545         }
546         return target->type->read_memory_imp(target, address, size, count, buffer);
547 }
548
549 static int target_soft_reset_halt_imp(struct target *target)
550 {
551         if (!target_was_examined(target))
552         {
553                 LOG_ERROR("Target not examined yet");
554                 return ERROR_FAIL;
555         }
556         if (!target->type->soft_reset_halt_imp) {
557                 LOG_ERROR("Target %s does not support soft_reset_halt",
558                                 target_name(target));
559                 return ERROR_FAIL;
560         }
561         return target->type->soft_reset_halt_imp(target);
562 }
563
564 static int target_run_algorithm_imp(struct target *target, int num_mem_params, struct mem_param *mem_params, int num_reg_params, struct reg_param *reg_param, uint32_t entry_point, uint32_t exit_point, int timeout_ms, void *arch_info)
565 {
566         if (!target_was_examined(target))
567         {
568                 LOG_ERROR("Target not examined yet");
569                 return ERROR_FAIL;
570         }
571         return target->type->run_algorithm_imp(target, num_mem_params, mem_params, num_reg_params, reg_param, entry_point, exit_point, timeout_ms, arch_info);
572 }
573
574 int target_read_memory(struct target *target,
575                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
576 {
577         return target->type->read_memory(target, address, size, count, buffer);
578 }
579
580 int target_read_phys_memory(struct target *target,
581                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
582 {
583         return target->type->read_phys_memory(target, address, size, count, buffer);
584 }
585
586 int target_write_memory(struct target *target,
587                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
588 {
589         return target->type->write_memory(target, address, size, count, buffer);
590 }
591
592 int target_write_phys_memory(struct target *target,
593                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
594 {
595         return target->type->write_phys_memory(target, address, size, count, buffer);
596 }
597
598 int target_bulk_write_memory(struct target *target,
599                 uint32_t address, uint32_t count, uint8_t *buffer)
600 {
601         return target->type->bulk_write_memory(target, address, count, buffer);
602 }
603
604 int target_add_breakpoint(struct target *target,
605                 struct breakpoint *breakpoint)
606 {
607         if (target->state != TARGET_HALTED) {
608                 LOG_WARNING("target %s is not halted", target->cmd_name);
609                 return ERROR_TARGET_NOT_HALTED;
610         }
611         return target->type->add_breakpoint(target, breakpoint);
612 }
613 int target_remove_breakpoint(struct target *target,
614                 struct breakpoint *breakpoint)
615 {
616         return target->type->remove_breakpoint(target, breakpoint);
617 }
618
619 int target_add_watchpoint(struct target *target,
620                 struct watchpoint *watchpoint)
621 {
622         if (target->state != TARGET_HALTED) {
623                 LOG_WARNING("target %s is not halted", target->cmd_name);
624                 return ERROR_TARGET_NOT_HALTED;
625         }
626         return target->type->add_watchpoint(target, watchpoint);
627 }
628 int target_remove_watchpoint(struct target *target,
629                 struct watchpoint *watchpoint)
630 {
631         return target->type->remove_watchpoint(target, watchpoint);
632 }
633
634 int target_get_gdb_reg_list(struct target *target,
635                 struct reg **reg_list[], int *reg_list_size)
636 {
637         return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
638 }
639 int target_step(struct target *target,
640                 int current, uint32_t address, int handle_breakpoints)
641 {
642         return target->type->step(target, current, address, handle_breakpoints);
643 }
644
645
646 int target_run_algorithm(struct target *target,
647                 int num_mem_params, struct mem_param *mem_params,
648                 int num_reg_params, struct reg_param *reg_param,
649                 uint32_t entry_point, uint32_t exit_point,
650                 int timeout_ms, void *arch_info)
651 {
652         return target->type->run_algorithm(target,
653                         num_mem_params, mem_params, num_reg_params, reg_param,
654                         entry_point, exit_point, timeout_ms, arch_info);
655 }
656
657 /**
658  * Reset the @c examined flag for the given target.
659  * Pure paranoia -- targets are zeroed on allocation.
660  */
661 static void target_reset_examined(struct target *target)
662 {
663         target->examined = false;
664 }
665
666 static int
667 err_read_phys_memory(struct target *target, uint32_t address,
668                 uint32_t size, uint32_t count, uint8_t *buffer)
669 {
670         LOG_ERROR("Not implemented: %s", __func__);
671         return ERROR_FAIL;
672 }
673
674 static int
675 err_write_phys_memory(struct target *target, uint32_t address,
676                 uint32_t size, uint32_t count, uint8_t *buffer)
677 {
678         LOG_ERROR("Not implemented: %s", __func__);
679         return ERROR_FAIL;
680 }
681
682 static int handle_target(void *priv);
683
684 int target_init(struct command_context *cmd_ctx)
685 {
686         struct target *target;
687         int retval;
688
689         for (target = all_targets; target; target = target->next) {
690                 struct target_type *type = target->type;
691
692                 target_reset_examined(target);
693                 if (target->type->examine == NULL)
694                 {
695                         target->type->examine = default_examine;
696                 }
697
698                 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
699                 {
700                         LOG_ERROR("target '%s' init failed", target_name(target));
701                         return retval;
702                 }
703
704
705                 /**
706                  * @todo get rid of those *memory_imp() methods, now that all
707                  * callers are using target_*_memory() accessors ... and make
708                  * sure the "physical" paths handle the same issues.
709                  */
710
711                 /* a non-invasive way(in terms of patches) to add some code that
712                  * runs before the type->write/read_memory implementation
713                  */
714                 target->type->write_memory_imp = target->type->write_memory;
715                 target->type->write_memory = target_write_memory_imp;
716                 target->type->read_memory_imp = target->type->read_memory;
717                 target->type->read_memory = target_read_memory_imp;
718                 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
719                 target->type->soft_reset_halt = target_soft_reset_halt_imp;
720                 target->type->run_algorithm_imp = target->type->run_algorithm;
721                 target->type->run_algorithm = target_run_algorithm_imp;
722
723                 /* Sanity-check MMU support ... stub in what we must, to help
724                  * implement it in stages, but warn if we need to do so.
725                  */
726                 if (type->mmu) {
727                         if (type->write_phys_memory == NULL) {
728                                 LOG_ERROR("type '%s' is missing %s",
729                                                 type->name,
730                                                 "write_phys_memory");
731                                 type->write_phys_memory = err_write_phys_memory;
732                         }
733                         if (type->read_phys_memory == NULL) {
734                                 LOG_ERROR("type '%s' is missing %s",
735                                                 type->name,
736                                                 "read_phys_memory");
737                                 type->read_phys_memory = err_read_phys_memory;
738                         }
739                         if (type->virt2phys == NULL) {
740                                 LOG_ERROR("type '%s' is missing %s",
741                                                 type->name,
742                                                 "virt2phys");
743                                 type->virt2phys = identity_virt2phys;
744                         }
745
746                 /* Make sure no-MMU targets all behave the same:  make no
747                  * distinction between physical and virtual addresses, and
748                  * ensure that virt2phys() is always an identity mapping.
749                  */
750                 } else {
751                         if (type->write_phys_memory
752                                         || type->read_phys_memory
753                                         || type->virt2phys)
754                                 LOG_WARNING("type '%s' has broken MMU hooks",
755                                                 type->name);
756
757                         type->mmu = no_mmu;
758                         type->write_phys_memory = type->write_memory;
759                         type->read_phys_memory = type->read_memory;
760                         type->virt2phys = identity_virt2phys;
761                 }
762         }
763
764         if (all_targets)
765         {
766                 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
767                         return retval;
768                 if ((retval = target_register_timer_callback(&handle_target, 100, 1, cmd_ctx->interp)) != ERROR_OK)
769                         return retval;
770         }
771
772         return ERROR_OK;
773 }
774
775 int target_register_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
776 {
777         struct target_event_callback **callbacks_p = &target_event_callbacks;
778
779         if (callback == NULL)
780         {
781                 return ERROR_INVALID_ARGUMENTS;
782         }
783
784         if (*callbacks_p)
785         {
786                 while ((*callbacks_p)->next)
787                         callbacks_p = &((*callbacks_p)->next);
788                 callbacks_p = &((*callbacks_p)->next);
789         }
790
791         (*callbacks_p) = malloc(sizeof(struct target_event_callback));
792         (*callbacks_p)->callback = callback;
793         (*callbacks_p)->priv = priv;
794         (*callbacks_p)->next = NULL;
795
796         return ERROR_OK;
797 }
798
799 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
800 {
801         struct target_timer_callback **callbacks_p = &target_timer_callbacks;
802         struct timeval now;
803
804         if (callback == NULL)
805         {
806                 return ERROR_INVALID_ARGUMENTS;
807         }
808
809         if (*callbacks_p)
810         {
811                 while ((*callbacks_p)->next)
812                         callbacks_p = &((*callbacks_p)->next);
813                 callbacks_p = &((*callbacks_p)->next);
814         }
815
816         (*callbacks_p) = malloc(sizeof(struct target_timer_callback));
817         (*callbacks_p)->callback = callback;
818         (*callbacks_p)->periodic = periodic;
819         (*callbacks_p)->time_ms = time_ms;
820
821         gettimeofday(&now, NULL);
822         (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
823         time_ms -= (time_ms % 1000);
824         (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
825         if ((*callbacks_p)->when.tv_usec > 1000000)
826         {
827                 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
828                 (*callbacks_p)->when.tv_sec += 1;
829         }
830
831         (*callbacks_p)->priv = priv;
832         (*callbacks_p)->next = NULL;
833
834         return ERROR_OK;
835 }
836
837 int target_unregister_event_callback(int (*callback)(struct target *target, enum target_event event, void *priv), void *priv)
838 {
839         struct target_event_callback **p = &target_event_callbacks;
840         struct target_event_callback *c = target_event_callbacks;
841
842         if (callback == NULL)
843         {
844                 return ERROR_INVALID_ARGUMENTS;
845         }
846
847         while (c)
848         {
849                 struct target_event_callback *next = c->next;
850                 if ((c->callback == callback) && (c->priv == priv))
851                 {
852                         *p = next;
853                         free(c);
854                         return ERROR_OK;
855                 }
856                 else
857                         p = &(c->next);
858                 c = next;
859         }
860
861         return ERROR_OK;
862 }
863
864 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
865 {
866         struct target_timer_callback **p = &target_timer_callbacks;
867         struct target_timer_callback *c = target_timer_callbacks;
868
869         if (callback == NULL)
870         {
871                 return ERROR_INVALID_ARGUMENTS;
872         }
873
874         while (c)
875         {
876                 struct target_timer_callback *next = c->next;
877                 if ((c->callback == callback) && (c->priv == priv))
878                 {
879                         *p = next;
880                         free(c);
881                         return ERROR_OK;
882                 }
883                 else
884                         p = &(c->next);
885                 c = next;
886         }
887
888         return ERROR_OK;
889 }
890
891 int target_call_event_callbacks(struct target *target, enum target_event event)
892 {
893         struct target_event_callback *callback = target_event_callbacks;
894         struct target_event_callback *next_callback;
895
896         if (event == TARGET_EVENT_HALTED)
897         {
898                 /* execute early halted first */
899                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
900         }
901
902         LOG_DEBUG("target event %i (%s)",
903                           event,
904                           Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
905
906         target_handle_event(target, event);
907
908         while (callback)
909         {
910                 next_callback = callback->next;
911                 callback->callback(target, event, callback->priv);
912                 callback = next_callback;
913         }
914
915         return ERROR_OK;
916 }
917
918 static int target_timer_callback_periodic_restart(
919                 struct target_timer_callback *cb, struct timeval *now)
920 {
921         int time_ms = cb->time_ms;
922         cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
923         time_ms -= (time_ms % 1000);
924         cb->when.tv_sec = now->tv_sec + time_ms / 1000;
925         if (cb->when.tv_usec > 1000000)
926         {
927                 cb->when.tv_usec = cb->when.tv_usec - 1000000;
928                 cb->when.tv_sec += 1;
929         }
930         return ERROR_OK;
931 }
932
933 static int target_call_timer_callback(struct target_timer_callback *cb,
934                 struct timeval *now)
935 {
936         cb->callback(cb->priv);
937
938         if (cb->periodic)
939                 return target_timer_callback_periodic_restart(cb, now);
940
941         return target_unregister_timer_callback(cb->callback, cb->priv);
942 }
943
944 static int target_call_timer_callbacks_check_time(int checktime)
945 {
946         keep_alive();
947
948         struct timeval now;
949         gettimeofday(&now, NULL);
950
951         struct target_timer_callback *callback = target_timer_callbacks;
952         while (callback)
953         {
954                 // cleaning up may unregister and free this callback
955                 struct target_timer_callback *next_callback = callback->next;
956
957                 bool call_it = callback->callback &&
958                         ((!checktime && callback->periodic) ||
959                           now.tv_sec > callback->when.tv_sec ||
960                          (now.tv_sec == callback->when.tv_sec &&
961                           now.tv_usec >= callback->when.tv_usec));
962
963                 if (call_it)
964                 {
965                         int retval = target_call_timer_callback(callback, &now);
966                         if (retval != ERROR_OK)
967                                 return retval;
968                 }
969
970                 callback = next_callback;
971         }
972
973         return ERROR_OK;
974 }
975
976 int target_call_timer_callbacks(void)
977 {
978         return target_call_timer_callbacks_check_time(1);
979 }
980
981 /* invoke periodic callbacks immediately */
982 int target_call_timer_callbacks_now(void)
983 {
984         return target_call_timer_callbacks_check_time(0);
985 }
986
987 int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
988 {
989         struct working_area *c = target->working_areas;
990         struct working_area *new_wa = NULL;
991
992         /* Reevaluate working area address based on MMU state*/
993         if (target->working_areas == NULL)
994         {
995                 int retval;
996                 int enabled;
997
998                 retval = target->type->mmu(target, &enabled);
999                 if (retval != ERROR_OK)
1000                 {
1001                         return retval;
1002                 }
1003
1004                 if (!enabled) {
1005                         if (target->working_area_phys_spec) {
1006                                 LOG_DEBUG("MMU disabled, using physical "
1007                                         "address for working memory 0x%08x",
1008                                         (unsigned)target->working_area_phys);
1009                                 target->working_area = target->working_area_phys;
1010                         } else {
1011                                 LOG_ERROR("No working memory available. "
1012                                         "Specify -work-area-phys to target.");
1013                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1014                         }
1015                 } else {
1016                         if (target->working_area_virt_spec) {
1017                                 LOG_DEBUG("MMU enabled, using virtual "
1018                                         "address for working memory 0x%08x",
1019                                         (unsigned)target->working_area_virt);
1020                                 target->working_area = target->working_area_virt;
1021                         } else {
1022                                 LOG_ERROR("No working memory available. "
1023                                         "Specify -work-area-virt to target.");
1024                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1025                         }
1026                 }
1027         }
1028
1029         /* only allocate multiples of 4 byte */
1030         if (size % 4)
1031         {
1032                 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1033                 size = (size + 3) & (~3);
1034         }
1035
1036         /* see if there's already a matching working area */
1037         while (c)
1038         {
1039                 if ((c->free) && (c->size == size))
1040                 {
1041                         new_wa = c;
1042                         break;
1043                 }
1044                 c = c->next;
1045         }
1046
1047         /* if not, allocate a new one */
1048         if (!new_wa)
1049         {
1050                 struct working_area **p = &target->working_areas;
1051                 uint32_t first_free = target->working_area;
1052                 uint32_t free_size = target->working_area_size;
1053
1054                 c = target->working_areas;
1055                 while (c)
1056                 {
1057                         first_free += c->size;
1058                         free_size -= c->size;
1059                         p = &c->next;
1060                         c = c->next;
1061                 }
1062
1063                 if (free_size < size)
1064                 {
1065                         LOG_WARNING("not enough working area available(requested %u, free %u)",
1066                                     (unsigned)(size), (unsigned)(free_size));
1067                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1068                 }
1069
1070                 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1071
1072                 new_wa = malloc(sizeof(struct working_area));
1073                 new_wa->next = NULL;
1074                 new_wa->size = size;
1075                 new_wa->address = first_free;
1076
1077                 if (target->backup_working_area)
1078                 {
1079                         int retval;
1080                         new_wa->backup = malloc(new_wa->size);
1081                         if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1082                         {
1083                                 free(new_wa->backup);
1084                                 free(new_wa);
1085                                 return retval;
1086                         }
1087                 }
1088                 else
1089                 {
1090                         new_wa->backup = NULL;
1091                 }
1092
1093                 /* put new entry in list */
1094                 *p = new_wa;
1095         }
1096
1097         /* mark as used, and return the new (reused) area */
1098         new_wa->free = 0;
1099         *area = new_wa;
1100
1101         /* user pointer */
1102         new_wa->user = area;
1103
1104         return ERROR_OK;
1105 }
1106
1107 int target_free_working_area_restore(struct target *target, struct working_area *area, int restore)
1108 {
1109         if (area->free)
1110                 return ERROR_OK;
1111
1112         if (restore && target->backup_working_area)
1113         {
1114                 int retval;
1115                 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1116                         return retval;
1117         }
1118
1119         area->free = 1;
1120
1121         /* mark user pointer invalid */
1122         *area->user = NULL;
1123         area->user = NULL;
1124
1125         return ERROR_OK;
1126 }
1127
1128 int target_free_working_area(struct target *target, struct working_area *area)
1129 {
1130         return target_free_working_area_restore(target, area, 1);
1131 }
1132
1133 /* free resources and restore memory, if restoring memory fails,
1134  * free up resources anyway
1135  */
1136 void target_free_all_working_areas_restore(struct target *target, int restore)
1137 {
1138         struct working_area *c = target->working_areas;
1139
1140         while (c)
1141         {
1142                 struct working_area *next = c->next;
1143                 target_free_working_area_restore(target, c, restore);
1144
1145                 if (c->backup)
1146                         free(c->backup);
1147
1148                 free(c);
1149
1150                 c = next;
1151         }
1152
1153         target->working_areas = NULL;
1154 }
1155
1156 void target_free_all_working_areas(struct target *target)
1157 {
1158         target_free_all_working_areas_restore(target, 1);
1159 }
1160
1161 int target_arch_state(struct target *target)
1162 {
1163         int retval;
1164         if (target == NULL)
1165         {
1166                 LOG_USER("No target has been configured");
1167                 return ERROR_OK;
1168         }
1169
1170         LOG_USER("target state: %s", target_state_name( target ));
1171
1172         if (target->state != TARGET_HALTED)
1173                 return ERROR_OK;
1174
1175         retval = target->type->arch_state(target);
1176         return retval;
1177 }
1178
1179 /* Single aligned words are guaranteed to use 16 or 32 bit access
1180  * mode respectively, otherwise data is handled as quickly as
1181  * possible
1182  */
1183 int target_write_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1184 {
1185         int retval;
1186         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1187                   (int)size, (unsigned)address);
1188
1189         if (!target_was_examined(target))
1190         {
1191                 LOG_ERROR("Target not examined yet");
1192                 return ERROR_FAIL;
1193         }
1194
1195         if (size == 0) {
1196                 return ERROR_OK;
1197         }
1198
1199         if ((address + size - 1) < address)
1200         {
1201                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1202                 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1203                                   (unsigned)address,
1204                                   (unsigned)size);
1205                 return ERROR_FAIL;
1206         }
1207
1208         if (((address % 2) == 0) && (size == 2))
1209         {
1210                 return target_write_memory(target, address, 2, 1, buffer);
1211         }
1212
1213         /* handle unaligned head bytes */
1214         if (address % 4)
1215         {
1216                 uint32_t unaligned = 4 - (address % 4);
1217
1218                 if (unaligned > size)
1219                         unaligned = size;
1220
1221                 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1222                         return retval;
1223
1224                 buffer += unaligned;
1225                 address += unaligned;
1226                 size -= unaligned;
1227         }
1228
1229         /* handle aligned words */
1230         if (size >= 4)
1231         {
1232                 int aligned = size - (size % 4);
1233
1234                 /* use bulk writes above a certain limit. This may have to be changed */
1235                 if (aligned > 128)
1236                 {
1237                         if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1238                                 return retval;
1239                 }
1240                 else
1241                 {
1242                         if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1243                                 return retval;
1244                 }
1245
1246                 buffer += aligned;
1247                 address += aligned;
1248                 size -= aligned;
1249         }
1250
1251         /* handle tail writes of less than 4 bytes */
1252         if (size > 0)
1253         {
1254                 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1255                         return retval;
1256         }
1257
1258         return ERROR_OK;
1259 }
1260
1261 /* Single aligned words are guaranteed to use 16 or 32 bit access
1262  * mode respectively, otherwise data is handled as quickly as
1263  * possible
1264  */
1265 int target_read_buffer(struct target *target, uint32_t address, uint32_t size, uint8_t *buffer)
1266 {
1267         int retval;
1268         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1269                           (int)size, (unsigned)address);
1270
1271         if (!target_was_examined(target))
1272         {
1273                 LOG_ERROR("Target not examined yet");
1274                 return ERROR_FAIL;
1275         }
1276
1277         if (size == 0) {
1278                 return ERROR_OK;
1279         }
1280
1281         if ((address + size - 1) < address)
1282         {
1283                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1284                 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1285                                   address,
1286                                   size);
1287                 return ERROR_FAIL;
1288         }
1289
1290         if (((address % 2) == 0) && (size == 2))
1291         {
1292                 return target_read_memory(target, address, 2, 1, buffer);
1293         }
1294
1295         /* handle unaligned head bytes */
1296         if (address % 4)
1297         {
1298                 uint32_t unaligned = 4 - (address % 4);
1299
1300                 if (unaligned > size)
1301                         unaligned = size;
1302
1303                 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1304                         return retval;
1305
1306                 buffer += unaligned;
1307                 address += unaligned;
1308                 size -= unaligned;
1309         }
1310
1311         /* handle aligned words */
1312         if (size >= 4)
1313         {
1314                 int aligned = size - (size % 4);
1315
1316                 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1317                         return retval;
1318
1319                 buffer += aligned;
1320                 address += aligned;
1321                 size -= aligned;
1322         }
1323
1324         /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1325         if(size >=2)
1326         {
1327                 int aligned = size - (size%2);
1328                 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1329                 if (retval != ERROR_OK)
1330                         return retval;
1331
1332                 buffer += aligned;
1333                 address += aligned;
1334                 size -= aligned;
1335         }
1336         /* handle tail writes of less than 4 bytes */
1337         if (size > 0)
1338         {
1339                 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1340                         return retval;
1341         }
1342
1343         return ERROR_OK;
1344 }
1345
1346 int target_checksum_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* crc)
1347 {
1348         uint8_t *buffer;
1349         int retval;
1350         uint32_t i;
1351         uint32_t checksum = 0;
1352         if (!target_was_examined(target))
1353         {
1354                 LOG_ERROR("Target not examined yet");
1355                 return ERROR_FAIL;
1356         }
1357
1358         if ((retval = target->type->checksum_memory(target, address,
1359                 size, &checksum)) != ERROR_OK)
1360         {
1361                 buffer = malloc(size);
1362                 if (buffer == NULL)
1363                 {
1364                         LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1365                         return ERROR_INVALID_ARGUMENTS;
1366                 }
1367                 retval = target_read_buffer(target, address, size, buffer);
1368                 if (retval != ERROR_OK)
1369                 {
1370                         free(buffer);
1371                         return retval;
1372                 }
1373
1374                 /* convert to target endianess */
1375                 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1376                 {
1377                         uint32_t target_data;
1378                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1379                         target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1380                 }
1381
1382                 retval = image_calculate_checksum(buffer, size, &checksum);
1383                 free(buffer);
1384         }
1385
1386         *crc = checksum;
1387
1388         return retval;
1389 }
1390
1391 int target_blank_check_memory(struct target *target, uint32_t address, uint32_t size, uint32_t* blank)
1392 {
1393         int retval;
1394         if (!target_was_examined(target))
1395         {
1396                 LOG_ERROR("Target not examined yet");
1397                 return ERROR_FAIL;
1398         }
1399
1400         if (target->type->blank_check_memory == 0)
1401                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1402
1403         retval = target->type->blank_check_memory(target, address, size, blank);
1404
1405         return retval;
1406 }
1407
1408 int target_read_u32(struct target *target, uint32_t address, uint32_t *value)
1409 {
1410         uint8_t value_buf[4];
1411         if (!target_was_examined(target))
1412         {
1413                 LOG_ERROR("Target not examined yet");
1414                 return ERROR_FAIL;
1415         }
1416
1417         int retval = target_read_memory(target, address, 4, 1, value_buf);
1418
1419         if (retval == ERROR_OK)
1420         {
1421                 *value = target_buffer_get_u32(target, value_buf);
1422                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1423                                   address,
1424                                   *value);
1425         }
1426         else
1427         {
1428                 *value = 0x0;
1429                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1430                                   address);
1431         }
1432
1433         return retval;
1434 }
1435
1436 int target_read_u16(struct target *target, uint32_t address, uint16_t *value)
1437 {
1438         uint8_t value_buf[2];
1439         if (!target_was_examined(target))
1440         {
1441                 LOG_ERROR("Target not examined yet");
1442                 return ERROR_FAIL;
1443         }
1444
1445         int retval = target_read_memory(target, address, 2, 1, value_buf);
1446
1447         if (retval == ERROR_OK)
1448         {
1449                 *value = target_buffer_get_u16(target, value_buf);
1450                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1451                                   address,
1452                                   *value);
1453         }
1454         else
1455         {
1456                 *value = 0x0;
1457                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1458                                   address);
1459         }
1460
1461         return retval;
1462 }
1463
1464 int target_read_u8(struct target *target, uint32_t address, uint8_t *value)
1465 {
1466         int retval = target_read_memory(target, address, 1, 1, value);
1467         if (!target_was_examined(target))
1468         {
1469                 LOG_ERROR("Target not examined yet");
1470                 return ERROR_FAIL;
1471         }
1472
1473         if (retval == ERROR_OK)
1474         {
1475                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1476                                   address,
1477                                   *value);
1478         }
1479         else
1480         {
1481                 *value = 0x0;
1482                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1483                                   address);
1484         }
1485
1486         return retval;
1487 }
1488
1489 int target_write_u32(struct target *target, uint32_t address, uint32_t value)
1490 {
1491         int retval;
1492         uint8_t value_buf[4];
1493         if (!target_was_examined(target))
1494         {
1495                 LOG_ERROR("Target not examined yet");
1496                 return ERROR_FAIL;
1497         }
1498
1499         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1500                           address,
1501                           value);
1502
1503         target_buffer_set_u32(target, value_buf, value);
1504         if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1505         {
1506                 LOG_DEBUG("failed: %i", retval);
1507         }
1508
1509         return retval;
1510 }
1511
1512 int target_write_u16(struct target *target, uint32_t address, uint16_t value)
1513 {
1514         int retval;
1515         uint8_t value_buf[2];
1516         if (!target_was_examined(target))
1517         {
1518                 LOG_ERROR("Target not examined yet");
1519                 return ERROR_FAIL;
1520         }
1521
1522         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1523                           address,
1524                           value);
1525
1526         target_buffer_set_u16(target, value_buf, value);
1527         if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1528         {
1529                 LOG_DEBUG("failed: %i", retval);
1530         }
1531
1532         return retval;
1533 }
1534
1535 int target_write_u8(struct target *target, uint32_t address, uint8_t value)
1536 {
1537         int retval;
1538         if (!target_was_examined(target))
1539         {
1540                 LOG_ERROR("Target not examined yet");
1541                 return ERROR_FAIL;
1542         }
1543
1544         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1545                           address, value);
1546
1547         if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1548         {
1549                 LOG_DEBUG("failed: %i", retval);
1550         }
1551
1552         return retval;
1553 }
1554
1555 COMMAND_HANDLER(handle_targets_command)
1556 {
1557         struct target *target = all_targets;
1558
1559         if (CMD_ARGC == 1)
1560         {
1561                 target = get_target(CMD_ARGV[0]);
1562                 if (target == NULL) {
1563                         command_print(CMD_CTX,"Target: %s is unknown, try one of:\n", CMD_ARGV[0]);
1564                         goto DumpTargets;
1565                 }
1566                 if (!target->tap->enabled) {
1567                         command_print(CMD_CTX,"Target: TAP %s is disabled, "
1568                                         "can't be the current target\n",
1569                                         target->tap->dotted_name);
1570                         return ERROR_FAIL;
1571                 }
1572
1573                 CMD_CTX->current_target = target->target_number;
1574                 return ERROR_OK;
1575         }
1576 DumpTargets:
1577
1578         target = all_targets;
1579         command_print(CMD_CTX, "    TargetName         Type       Endian TapName            State       ");
1580         command_print(CMD_CTX, "--  ------------------ ---------- ------ ------------------ ------------");
1581         while (target)
1582         {
1583                 const char *state;
1584                 char marker = ' ';
1585
1586                 if (target->tap->enabled)
1587                         state = target_state_name( target );
1588                 else
1589                         state = "tap-disabled";
1590
1591                 if (CMD_CTX->current_target == target->target_number)
1592                         marker = '*';
1593
1594                 /* keep columns lined up to match the headers above */
1595                 command_print(CMD_CTX, "%2d%c %-18s %-10s %-6s %-18s %s",
1596                                           target->target_number,
1597                                           marker,
1598                                           target_name(target),
1599                                           target_type_name(target),
1600                                           Jim_Nvp_value2name_simple(nvp_target_endian,
1601                                                                 target->endianness)->name,
1602                                           target->tap->dotted_name,
1603                                           state);
1604                 target = target->next;
1605         }
1606
1607         return ERROR_OK;
1608 }
1609
1610 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1611
1612 static int powerDropout;
1613 static int srstAsserted;
1614
1615 static int runPowerRestore;
1616 static int runPowerDropout;
1617 static int runSrstAsserted;
1618 static int runSrstDeasserted;
1619
1620 static int sense_handler(void)
1621 {
1622         static int prevSrstAsserted = 0;
1623         static int prevPowerdropout = 0;
1624
1625         int retval;
1626         if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1627                 return retval;
1628
1629         int powerRestored;
1630         powerRestored = prevPowerdropout && !powerDropout;
1631         if (powerRestored)
1632         {
1633                 runPowerRestore = 1;
1634         }
1635
1636         long long current = timeval_ms();
1637         static long long lastPower = 0;
1638         int waitMore = lastPower + 2000 > current;
1639         if (powerDropout && !waitMore)
1640         {
1641                 runPowerDropout = 1;
1642                 lastPower = current;
1643         }
1644
1645         if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1646                 return retval;
1647
1648         int srstDeasserted;
1649         srstDeasserted = prevSrstAsserted && !srstAsserted;
1650
1651         static long long lastSrst = 0;
1652         waitMore = lastSrst + 2000 > current;
1653         if (srstDeasserted && !waitMore)
1654         {
1655                 runSrstDeasserted = 1;
1656                 lastSrst = current;
1657         }
1658
1659         if (!prevSrstAsserted && srstAsserted)
1660         {
1661                 runSrstAsserted = 1;
1662         }
1663
1664         prevSrstAsserted = srstAsserted;
1665         prevPowerdropout = powerDropout;
1666
1667         if (srstDeasserted || powerRestored)
1668         {
1669                 /* Other than logging the event we can't do anything here.
1670                  * Issuing a reset is a particularly bad idea as we might
1671                  * be inside a reset already.
1672                  */
1673         }
1674
1675         return ERROR_OK;
1676 }
1677
1678 static void target_call_event_callbacks_all(enum target_event e) {
1679         struct target *target;
1680         target = all_targets;
1681         while (target) {
1682                 target_call_event_callbacks(target, e);
1683                 target = target->next;
1684         }
1685 }
1686
1687 /* process target state changes */
1688 static int handle_target(void *priv)
1689 {
1690         Jim_Interp *interp = (Jim_Interp *)priv;
1691         int retval = ERROR_OK;
1692
1693         /* we do not want to recurse here... */
1694         static int recursive = 0;
1695         if (! recursive)
1696         {
1697                 recursive = 1;
1698                 sense_handler();
1699                 /* danger! running these procedures can trigger srst assertions and power dropouts.
1700                  * We need to avoid an infinite loop/recursion here and we do that by
1701                  * clearing the flags after running these events.
1702                  */
1703                 int did_something = 0;
1704                 if (runSrstAsserted)
1705                 {
1706                         target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1707                         Jim_Eval(interp, "srst_asserted");
1708                         did_something = 1;
1709                 }
1710                 if (runSrstDeasserted)
1711                 {
1712                         Jim_Eval(interp, "srst_deasserted");
1713                         did_something = 1;
1714                 }
1715                 if (runPowerDropout)
1716                 {
1717                         target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1718                         Jim_Eval(interp, "power_dropout");
1719                         did_something = 1;
1720                 }
1721                 if (runPowerRestore)
1722                 {
1723                         Jim_Eval(interp, "power_restore");
1724                         did_something = 1;
1725                 }
1726
1727                 if (did_something)
1728                 {
1729                         /* clear detect flags */
1730                         sense_handler();
1731                 }
1732
1733                 /* clear action flags */
1734
1735                 runSrstAsserted = 0;
1736                 runSrstDeasserted = 0;
1737                 runPowerRestore = 0;
1738                 runPowerDropout = 0;
1739
1740                 recursive = 0;
1741         }
1742
1743         /* Poll targets for state changes unless that's globally disabled.
1744          * Skip targets that are currently disabled.
1745          */
1746         for (struct target *target = all_targets;
1747                         is_jtag_poll_safe() && target;
1748                         target = target->next)
1749         {
1750                 if (!target->tap->enabled)
1751                         continue;
1752
1753                 /* only poll target if we've got power and srst isn't asserted */
1754                 if (!powerDropout && !srstAsserted)
1755                 {
1756                         /* polling may fail silently until the target has been examined */
1757                         if ((retval = target_poll(target)) != ERROR_OK)
1758                         {
1759                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1760                                 return retval;
1761                         }
1762                 }
1763         }
1764
1765         return retval;
1766 }
1767
1768 COMMAND_HANDLER(handle_reg_command)
1769 {
1770         struct target *target;
1771         struct reg *reg = NULL;
1772         unsigned count = 0;
1773         char *value;
1774
1775         LOG_DEBUG("-");
1776
1777         target = get_current_target(CMD_CTX);
1778
1779         /* list all available registers for the current target */
1780         if (CMD_ARGC == 0)
1781         {
1782                 struct reg_cache *cache = target->reg_cache;
1783
1784                 count = 0;
1785                 while (cache)
1786                 {
1787                         unsigned i;
1788
1789                         command_print(CMD_CTX, "===== %s", cache->name);
1790
1791                         for (i = 0, reg = cache->reg_list;
1792                                         i < cache->num_regs;
1793                                         i++, reg++, count++)
1794                         {
1795                                 /* only print cached values if they are valid */
1796                                 if (reg->valid) {
1797                                         value = buf_to_str(reg->value,
1798                                                         reg->size, 16);
1799                                         command_print(CMD_CTX,
1800                                                         "(%i) %s (/%" PRIu32 "): 0x%s%s",
1801                                                         count, reg->name,
1802                                                         reg->size, value,
1803                                                         reg->dirty
1804                                                                 ? " (dirty)"
1805                                                                 : "");
1806                                         free(value);
1807                                 } else {
1808                                         command_print(CMD_CTX, "(%i) %s (/%" PRIu32 ")",
1809                                                           count, reg->name,
1810                                                           reg->size) ;
1811                                 }
1812                         }
1813                         cache = cache->next;
1814                 }
1815
1816                 return ERROR_OK;
1817         }
1818
1819         /* access a single register by its ordinal number */
1820         if ((CMD_ARGV[0][0] >= '0') && (CMD_ARGV[0][0] <= '9'))
1821         {
1822                 unsigned num;
1823                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num);
1824
1825                 struct reg_cache *cache = target->reg_cache;
1826                 count = 0;
1827                 while (cache)
1828                 {
1829                         unsigned i;
1830                         for (i = 0; i < cache->num_regs; i++)
1831                         {
1832                                 if (count++ == num)
1833                                 {
1834                                         reg = &cache->reg_list[i];
1835                                         break;
1836                                 }
1837                         }
1838                         if (reg)
1839                                 break;
1840                         cache = cache->next;
1841                 }
1842
1843                 if (!reg)
1844                 {
1845                         command_print(CMD_CTX, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1846                         return ERROR_OK;
1847                 }
1848         } else /* access a single register by its name */
1849         {
1850                 reg = register_get_by_name(target->reg_cache, CMD_ARGV[0], 1);
1851
1852                 if (!reg)
1853                 {
1854                         command_print(CMD_CTX, "register %s not found in current target", CMD_ARGV[0]);
1855                         return ERROR_OK;
1856                 }
1857         }
1858
1859         /* display a register */
1860         if ((CMD_ARGC == 1) || ((CMD_ARGC == 2) && !((CMD_ARGV[1][0] >= '0') && (CMD_ARGV[1][0] <= '9'))))
1861         {
1862                 if ((CMD_ARGC == 2) && (strcmp(CMD_ARGV[1], "force") == 0))
1863                         reg->valid = 0;
1864
1865                 if (reg->valid == 0)
1866                 {
1867                         reg->type->get(reg);
1868                 }
1869                 value = buf_to_str(reg->value, reg->size, 16);
1870                 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1871                 free(value);
1872                 return ERROR_OK;
1873         }
1874
1875         /* set register value */
1876         if (CMD_ARGC == 2)
1877         {
1878                 uint8_t *buf = malloc(DIV_ROUND_UP(reg->size, 8));
1879                 str_to_buf(CMD_ARGV[1], strlen(CMD_ARGV[1]), buf, reg->size, 0);
1880
1881                 reg->type->set(reg, buf);
1882
1883                 value = buf_to_str(reg->value, reg->size, 16);
1884                 command_print(CMD_CTX, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
1885                 free(value);
1886
1887                 free(buf);
1888
1889                 return ERROR_OK;
1890         }
1891
1892         command_print(CMD_CTX, "usage: reg <#|name> [value]");
1893
1894         return ERROR_OK;
1895 }
1896
1897 COMMAND_HANDLER(handle_poll_command)
1898 {
1899         int retval = ERROR_OK;
1900         struct target *target = get_current_target(CMD_CTX);
1901
1902         if (CMD_ARGC == 0)
1903         {
1904                 command_print(CMD_CTX, "background polling: %s",
1905                                 jtag_poll_get_enabled() ? "on" : "off");
1906                 command_print(CMD_CTX, "TAP: %s (%s)",
1907                                 target->tap->dotted_name,
1908                                 target->tap->enabled ? "enabled" : "disabled");
1909                 if (!target->tap->enabled)
1910                         return ERROR_OK;
1911                 if ((retval = target_poll(target)) != ERROR_OK)
1912                         return retval;
1913                 if ((retval = target_arch_state(target)) != ERROR_OK)
1914                         return retval;
1915         }
1916         else if (CMD_ARGC == 1)
1917         {
1918                 bool enable;
1919                 COMMAND_PARSE_ON_OFF(CMD_ARGV[0], enable);
1920                 jtag_poll_set_enabled(enable);
1921         }
1922         else
1923         {
1924                 return ERROR_COMMAND_SYNTAX_ERROR;
1925         }
1926
1927         return retval;
1928 }
1929
1930 COMMAND_HANDLER(handle_wait_halt_command)
1931 {
1932         if (CMD_ARGC > 1)
1933                 return ERROR_COMMAND_SYNTAX_ERROR;
1934
1935         unsigned ms = 5000;
1936         if (1 == CMD_ARGC)
1937         {
1938                 int retval = parse_uint(CMD_ARGV[0], &ms);
1939                 if (ERROR_OK != retval)
1940                 {
1941                         command_print(CMD_CTX, "usage: %s [seconds]", CMD_NAME);
1942                         return ERROR_COMMAND_SYNTAX_ERROR;
1943                 }
1944                 // convert seconds (given) to milliseconds (needed)
1945                 ms *= 1000;
1946         }
1947
1948         struct target *target = get_current_target(CMD_CTX);
1949         return target_wait_state(target, TARGET_HALTED, ms);
1950 }
1951
1952 /* wait for target state to change. The trick here is to have a low
1953  * latency for short waits and not to suck up all the CPU time
1954  * on longer waits.
1955  *
1956  * After 500ms, keep_alive() is invoked
1957  */
1958 int target_wait_state(struct target *target, enum target_state state, int ms)
1959 {
1960         int retval;
1961         long long then = 0, cur;
1962         int once = 1;
1963
1964         for (;;)
1965         {
1966                 if ((retval = target_poll(target)) != ERROR_OK)
1967                         return retval;
1968                 if (target->state == state)
1969                 {
1970                         break;
1971                 }
1972                 cur = timeval_ms();
1973                 if (once)
1974                 {
1975                         once = 0;
1976                         then = timeval_ms();
1977                         LOG_DEBUG("waiting for target %s...",
1978                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1979                 }
1980
1981                 if (cur-then > 500)
1982                 {
1983                         keep_alive();
1984                 }
1985
1986                 if ((cur-then) > ms)
1987                 {
1988                         LOG_ERROR("timed out while waiting for target %s",
1989                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1990                         return ERROR_FAIL;
1991                 }
1992         }
1993
1994         return ERROR_OK;
1995 }
1996
1997 COMMAND_HANDLER(handle_halt_command)
1998 {
1999         LOG_DEBUG("-");
2000
2001         struct target *target = get_current_target(CMD_CTX);
2002         int retval = target_halt(target);
2003         if (ERROR_OK != retval)
2004                 return retval;
2005
2006         if (CMD_ARGC == 1)
2007         {
2008                 unsigned wait;
2009                 retval = parse_uint(CMD_ARGV[0], &wait);
2010                 if (ERROR_OK != retval)
2011                         return ERROR_COMMAND_SYNTAX_ERROR;
2012                 if (!wait)
2013                         return ERROR_OK;
2014         }
2015
2016         return CALL_COMMAND_HANDLER(handle_wait_halt_command);
2017 }
2018
2019 COMMAND_HANDLER(handle_soft_reset_halt_command)
2020 {
2021         struct target *target = get_current_target(CMD_CTX);
2022
2023         LOG_USER("requesting target halt and executing a soft reset");
2024
2025         target->type->soft_reset_halt(target);
2026
2027         return ERROR_OK;
2028 }
2029
2030 COMMAND_HANDLER(handle_reset_command)
2031 {
2032         if (CMD_ARGC > 1)
2033                 return ERROR_COMMAND_SYNTAX_ERROR;
2034
2035         enum target_reset_mode reset_mode = RESET_RUN;
2036         if (CMD_ARGC == 1)
2037         {
2038                 const Jim_Nvp *n;
2039                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, CMD_ARGV[0]);
2040                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2041                         return ERROR_COMMAND_SYNTAX_ERROR;
2042                 }
2043                 reset_mode = n->value;
2044         }
2045
2046         /* reset *all* targets */
2047         return target_process_reset(CMD_CTX, reset_mode);
2048 }
2049
2050
2051 COMMAND_HANDLER(handle_resume_command)
2052 {
2053         int current = 1;
2054         if (CMD_ARGC > 1)
2055                 return ERROR_COMMAND_SYNTAX_ERROR;
2056
2057         struct target *target = get_current_target(CMD_CTX);
2058         target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2059
2060         /* with no CMD_ARGV, resume from current pc, addr = 0,
2061          * with one arguments, addr = CMD_ARGV[0],
2062          * handle breakpoints, not debugging */
2063         uint32_t addr = 0;
2064         if (CMD_ARGC == 1)
2065         {
2066                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2067                 current = 0;
2068         }
2069
2070         return target_resume(target, current, addr, 1, 0);
2071 }
2072
2073 COMMAND_HANDLER(handle_step_command)
2074 {
2075         if (CMD_ARGC > 1)
2076                 return ERROR_COMMAND_SYNTAX_ERROR;
2077
2078         LOG_DEBUG("-");
2079
2080         /* with no CMD_ARGV, step from current pc, addr = 0,
2081          * with one argument addr = CMD_ARGV[0],
2082          * handle breakpoints, debugging */
2083         uint32_t addr = 0;
2084         int current_pc = 1;
2085         if (CMD_ARGC == 1)
2086         {
2087                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2088                 current_pc = 0;
2089         }
2090
2091         struct target *target = get_current_target(CMD_CTX);
2092
2093         return target->type->step(target, current_pc, addr, 1);
2094 }
2095
2096 static void handle_md_output(struct command_context *cmd_ctx,
2097                 struct target *target, uint32_t address, unsigned size,
2098                 unsigned count, const uint8_t *buffer)
2099 {
2100         const unsigned line_bytecnt = 32;
2101         unsigned line_modulo = line_bytecnt / size;
2102
2103         char output[line_bytecnt * 4 + 1];
2104         unsigned output_len = 0;
2105
2106         const char *value_fmt;
2107         switch (size) {
2108         case 4: value_fmt = "%8.8x "; break;
2109         case 2: value_fmt = "%4.2x "; break;
2110         case 1: value_fmt = "%2.2x "; break;
2111         default:
2112                 LOG_ERROR("invalid memory read size: %u", size);
2113                 exit(-1);
2114         }
2115
2116         for (unsigned i = 0; i < count; i++)
2117         {
2118                 if (i % line_modulo == 0)
2119                 {
2120                         output_len += snprintf(output + output_len,
2121                                         sizeof(output) - output_len,
2122                                         "0x%8.8x: ",
2123                                         (unsigned)(address + (i*size)));
2124                 }
2125
2126                 uint32_t value = 0;
2127                 const uint8_t *value_ptr = buffer + i * size;
2128                 switch (size) {
2129                 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2130                 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2131                 case 1: value = *value_ptr;
2132                 }
2133                 output_len += snprintf(output + output_len,
2134                                 sizeof(output) - output_len,
2135                                 value_fmt, value);
2136
2137                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2138                 {
2139                         command_print(cmd_ctx, "%s", output);
2140                         output_len = 0;
2141                 }
2142         }
2143 }
2144
2145 COMMAND_HANDLER(handle_md_command)
2146 {
2147         if (CMD_ARGC < 1)
2148                 return ERROR_COMMAND_SYNTAX_ERROR;
2149
2150         unsigned size = 0;
2151         switch (CMD_NAME[2]) {
2152         case 'w': size = 4; break;
2153         case 'h': size = 2; break;
2154         case 'b': size = 1; break;
2155         default: return ERROR_COMMAND_SYNTAX_ERROR;
2156         }
2157
2158         bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2159         int (*fn)(struct target *target,
2160                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2161         if (physical)
2162         {
2163                 CMD_ARGC--;
2164                 CMD_ARGV++;
2165                 fn=target_read_phys_memory;
2166         } else
2167         {
2168                 fn=target_read_memory;
2169         }
2170         if ((CMD_ARGC < 1) || (CMD_ARGC > 2))
2171         {
2172                 return ERROR_COMMAND_SYNTAX_ERROR;
2173         }
2174
2175         uint32_t address;
2176         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2177
2178         unsigned count = 1;
2179         if (CMD_ARGC == 2)
2180                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[1], count);
2181
2182         uint8_t *buffer = calloc(count, size);
2183
2184         struct target *target = get_current_target(CMD_CTX);
2185         int retval = fn(target, address, size, count, buffer);
2186         if (ERROR_OK == retval)
2187                 handle_md_output(CMD_CTX, target, address, size, count, buffer);
2188
2189         free(buffer);
2190
2191         return retval;
2192 }
2193
2194 COMMAND_HANDLER(handle_mw_command)
2195 {
2196         if (CMD_ARGC < 2)
2197         {
2198                 return ERROR_COMMAND_SYNTAX_ERROR;
2199         }
2200         bool physical=strcmp(CMD_ARGV[0], "phys")==0;
2201         int (*fn)(struct target *target,
2202                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2203         if (physical)
2204         {
2205                 CMD_ARGC--;
2206                 CMD_ARGV++;
2207                 fn=target_write_phys_memory;
2208         } else
2209         {
2210                 fn=target_write_memory;
2211         }
2212         if ((CMD_ARGC < 2) || (CMD_ARGC > 3))
2213                 return ERROR_COMMAND_SYNTAX_ERROR;
2214
2215         uint32_t address;
2216         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2217
2218         uint32_t value;
2219         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2220
2221         unsigned count = 1;
2222         if (CMD_ARGC == 3)
2223                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[2], count);
2224
2225         struct target *target = get_current_target(CMD_CTX);
2226         unsigned wordsize;
2227         uint8_t value_buf[4];
2228         switch (CMD_NAME[2])
2229         {
2230                 case 'w':
2231                         wordsize = 4;
2232                         target_buffer_set_u32(target, value_buf, value);
2233                         break;
2234                 case 'h':
2235                         wordsize = 2;
2236                         target_buffer_set_u16(target, value_buf, value);
2237                         break;
2238                 case 'b':
2239                         wordsize = 1;
2240                         value_buf[0] = value;
2241                         break;
2242                 default:
2243                         return ERROR_COMMAND_SYNTAX_ERROR;
2244         }
2245         for (unsigned i = 0; i < count; i++)
2246         {
2247                 int retval = fn(target,
2248                                 address + i * wordsize, wordsize, 1, value_buf);
2249                 if (ERROR_OK != retval)
2250                         return retval;
2251                 keep_alive();
2252         }
2253
2254         return ERROR_OK;
2255
2256 }
2257
2258 static COMMAND_HELPER(parse_load_image_command_CMD_ARGV, struct image *image,
2259                 uint32_t *min_address, uint32_t *max_address)
2260 {
2261         if (CMD_ARGC < 1 || CMD_ARGC > 5)
2262                 return ERROR_COMMAND_SYNTAX_ERROR;
2263
2264         /* a base address isn't always necessary,
2265          * default to 0x0 (i.e. don't relocate) */
2266         if (CMD_ARGC >= 2)
2267         {
2268                 uint32_t addr;
2269                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2270                 image->base_address = addr;
2271                 image->base_address_set = 1;
2272         }
2273         else
2274                 image->base_address_set = 0;
2275
2276         image->start_address_set = 0;
2277
2278         if (CMD_ARGC >= 4)
2279         {
2280                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], *min_address);
2281         }
2282         if (CMD_ARGC == 5)
2283         {
2284                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], *max_address);
2285                 // use size (given) to find max (required)
2286                 *max_address += *min_address;
2287         }
2288
2289         if (*min_address > *max_address)
2290                 return ERROR_COMMAND_SYNTAX_ERROR;
2291
2292         return ERROR_OK;
2293 }
2294
2295 COMMAND_HANDLER(handle_load_image_command)
2296 {
2297         uint8_t *buffer;
2298         size_t buf_cnt;
2299         uint32_t image_size;
2300         uint32_t min_address = 0;
2301         uint32_t max_address = 0xffffffff;
2302         int i;
2303         struct image image;
2304
2305         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
2306                         &image, &min_address, &max_address);
2307         if (ERROR_OK != retval)
2308                 return retval;
2309
2310         struct target *target = get_current_target(CMD_CTX);
2311
2312         struct duration bench;
2313         duration_start(&bench);
2314
2315         if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
2316         {
2317                 return ERROR_OK;
2318         }
2319
2320         image_size = 0x0;
2321         retval = ERROR_OK;
2322         for (i = 0; i < image.num_sections; i++)
2323         {
2324                 buffer = malloc(image.sections[i].size);
2325                 if (buffer == NULL)
2326                 {
2327                         command_print(CMD_CTX,
2328                                                   "error allocating buffer for section (%d bytes)",
2329                                                   (int)(image.sections[i].size));
2330                         break;
2331                 }
2332
2333                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2334                 {
2335                         free(buffer);
2336                         break;
2337                 }
2338
2339                 uint32_t offset = 0;
2340                 uint32_t length = buf_cnt;
2341
2342                 /* DANGER!!! beware of unsigned comparision here!!! */
2343
2344                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2345                                 (image.sections[i].base_address < max_address))
2346                 {
2347                         if (image.sections[i].base_address < min_address)
2348                         {
2349                                 /* clip addresses below */
2350                                 offset += min_address-image.sections[i].base_address;
2351                                 length -= offset;
2352                         }
2353
2354                         if (image.sections[i].base_address + buf_cnt > max_address)
2355                         {
2356                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2357                         }
2358
2359                         if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2360                         {
2361                                 free(buffer);
2362                                 break;
2363                         }
2364                         image_size += length;
2365                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8" PRIx32 "",
2366                                                   (unsigned int)length,
2367                                                   image.sections[i].base_address + offset);
2368                 }
2369
2370                 free(buffer);
2371         }
2372
2373         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2374         {
2375                 command_print(CMD_CTX, "downloaded %" PRIu32 " bytes "
2376                                 "in %fs (%0.3f kb/s)", image_size,
2377                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2378         }
2379
2380         image_close(&image);
2381
2382         return retval;
2383
2384 }
2385
2386 COMMAND_HANDLER(handle_dump_image_command)
2387 {
2388         struct fileio fileio;
2389
2390         uint8_t buffer[560];
2391         int retvaltemp;
2392
2393
2394         struct target *target = get_current_target(CMD_CTX);
2395
2396         if (CMD_ARGC != 3)
2397         {
2398                 command_print(CMD_CTX, "usage: dump_image <filename> <address> <size>");
2399                 return ERROR_OK;
2400         }
2401
2402         uint32_t address;
2403         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], address);
2404         uint32_t size;
2405         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], size);
2406
2407         if (fileio_open(&fileio, CMD_ARGV[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2408         {
2409                 return ERROR_OK;
2410         }
2411
2412         struct duration bench;
2413         duration_start(&bench);
2414
2415         int retval = ERROR_OK;
2416         while (size > 0)
2417         {
2418                 size_t size_written;
2419                 uint32_t this_run_size = (size > 560) ? 560 : size;
2420                 retval = target_read_buffer(target, address, this_run_size, buffer);
2421                 if (retval != ERROR_OK)
2422                 {
2423                         break;
2424                 }
2425
2426                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2427                 if (retval != ERROR_OK)
2428                 {
2429                         break;
2430                 }
2431
2432                 size -= this_run_size;
2433                 address += this_run_size;
2434         }
2435
2436         if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2437                 return retvaltemp;
2438
2439         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2440         {
2441                 command_print(CMD_CTX,
2442                                 "dumped %zu bytes in %fs (%0.3f kb/s)", fileio.size,
2443                                 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2444         }
2445
2446         return retval;
2447 }
2448
2449 static COMMAND_HELPER(handle_verify_image_command_internal, int verify)
2450 {
2451         uint8_t *buffer;
2452         size_t buf_cnt;
2453         uint32_t image_size;
2454         int i;
2455         int retval;
2456         uint32_t checksum = 0;
2457         uint32_t mem_checksum = 0;
2458
2459         struct image image;
2460
2461         struct target *target = get_current_target(CMD_CTX);
2462
2463         if (CMD_ARGC < 1)
2464         {
2465                 return ERROR_COMMAND_SYNTAX_ERROR;
2466         }
2467
2468         if (!target)
2469         {
2470                 LOG_ERROR("no target selected");
2471                 return ERROR_FAIL;
2472         }
2473
2474         struct duration bench;
2475         duration_start(&bench);
2476
2477         if (CMD_ARGC >= 2)
2478         {
2479                 uint32_t addr;
2480                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], addr);
2481                 image.base_address = addr;
2482                 image.base_address_set = 1;
2483         }
2484         else
2485         {
2486                 image.base_address_set = 0;
2487                 image.base_address = 0x0;
2488         }
2489
2490         image.start_address_set = 0;
2491
2492         if ((retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL)) != ERROR_OK)
2493         {
2494                 return retval;
2495         }
2496
2497         image_size = 0x0;
2498         retval = ERROR_OK;
2499         for (i = 0; i < image.num_sections; i++)
2500         {
2501                 buffer = malloc(image.sections[i].size);
2502                 if (buffer == NULL)
2503                 {
2504                         command_print(CMD_CTX,
2505                                                   "error allocating buffer for section (%d bytes)",
2506                                                   (int)(image.sections[i].size));
2507                         break;
2508                 }
2509                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2510                 {
2511                         free(buffer);
2512                         break;
2513                 }
2514
2515                 if (verify)
2516                 {
2517                         /* calculate checksum of image */
2518                         image_calculate_checksum(buffer, buf_cnt, &checksum);
2519
2520                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2521                         if (retval != ERROR_OK)
2522                         {
2523                                 free(buffer);
2524                                 break;
2525                         }
2526
2527                         if (checksum != mem_checksum)
2528                         {
2529                                 /* failed crc checksum, fall back to a binary compare */
2530                                 uint8_t *data;
2531
2532                                 command_print(CMD_CTX, "checksum mismatch - attempting binary compare");
2533
2534                                 data = (uint8_t*)malloc(buf_cnt);
2535
2536                                 /* Can we use 32bit word accesses? */
2537                                 int size = 1;
2538                                 int count = buf_cnt;
2539                                 if ((count % 4) == 0)
2540                                 {
2541                                         size *= 4;
2542                                         count /= 4;
2543                                 }
2544                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2545                                 if (retval == ERROR_OK)
2546                                 {
2547                                         uint32_t t;
2548                                         for (t = 0; t < buf_cnt; t++)
2549                                         {
2550                                                 if (data[t] != buffer[t])
2551                                                 {
2552                                                         command_print(CMD_CTX,
2553                                                                                   "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2554                                                                                   (unsigned)(t + image.sections[i].base_address),
2555                                                                                   data[t],
2556                                                                                   buffer[t]);
2557                                                         free(data);
2558                                                         free(buffer);
2559                                                         retval = ERROR_FAIL;
2560                                                         goto done;
2561                                                 }
2562                                                 if ((t%16384) == 0)
2563                                                 {
2564                                                         keep_alive();
2565                                                 }
2566                                         }
2567                                 }
2568
2569                                 free(data);
2570                         }
2571                 } else
2572                 {
2573                         command_print(CMD_CTX, "address 0x%08" PRIx32 " length 0x%08zx",
2574                                                   image.sections[i].base_address,
2575                                                   buf_cnt);
2576                 }
2577
2578                 free(buffer);
2579                 image_size += buf_cnt;
2580         }
2581 done:
2582         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2583         {
2584                 command_print(CMD_CTX, "verified %" PRIu32 " bytes "
2585                                 "in %fs (%0.3f kb/s)", image_size,
2586                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2587         }
2588
2589         image_close(&image);
2590
2591         return retval;
2592 }
2593
2594 COMMAND_HANDLER(handle_verify_image_command)
2595 {
2596         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 1);
2597 }
2598
2599 COMMAND_HANDLER(handle_test_image_command)
2600 {
2601         return CALL_COMMAND_HANDLER(handle_verify_image_command_internal, 0);
2602 }
2603
2604 static int handle_bp_command_list(struct command_context *cmd_ctx)
2605 {
2606         struct target *target = get_current_target(cmd_ctx);
2607         struct breakpoint *breakpoint = target->breakpoints;
2608         while (breakpoint)
2609         {
2610                 if (breakpoint->type == BKPT_SOFT)
2611                 {
2612                         char* buf = buf_to_str(breakpoint->orig_instr,
2613                                         breakpoint->length, 16);
2614                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2615                                         breakpoint->address,
2616                                         breakpoint->length,
2617                                         breakpoint->set, buf);
2618                         free(buf);
2619                 }
2620                 else
2621                 {
2622                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2623                                                   breakpoint->address,
2624                                                   breakpoint->length, breakpoint->set);
2625                 }
2626
2627                 breakpoint = breakpoint->next;
2628         }
2629         return ERROR_OK;
2630 }
2631
2632 static int handle_bp_command_set(struct command_context *cmd_ctx,
2633                 uint32_t addr, uint32_t length, int hw)
2634 {
2635         struct target *target = get_current_target(cmd_ctx);
2636         int retval = breakpoint_add(target, addr, length, hw);
2637         if (ERROR_OK == retval)
2638                 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2639         else
2640                 LOG_ERROR("Failure setting breakpoint");
2641         return retval;
2642 }
2643
2644 COMMAND_HANDLER(handle_bp_command)
2645 {
2646         if (CMD_ARGC == 0)
2647                 return handle_bp_command_list(CMD_CTX);
2648
2649         if (CMD_ARGC < 2 || CMD_ARGC > 3)
2650         {
2651                 command_print(CMD_CTX, "usage: bp <address> <length> ['hw']");
2652                 return ERROR_COMMAND_SYNTAX_ERROR;
2653         }
2654
2655         uint32_t addr;
2656         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2657         uint32_t length;
2658         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2659
2660         int hw = BKPT_SOFT;
2661         if (CMD_ARGC == 3)
2662         {
2663                 if (strcmp(CMD_ARGV[2], "hw") == 0)
2664                         hw = BKPT_HARD;
2665                 else
2666                         return ERROR_COMMAND_SYNTAX_ERROR;
2667         }
2668
2669         return handle_bp_command_set(CMD_CTX, addr, length, hw);
2670 }
2671
2672 COMMAND_HANDLER(handle_rbp_command)
2673 {
2674         if (CMD_ARGC != 1)
2675                 return ERROR_COMMAND_SYNTAX_ERROR;
2676
2677         uint32_t addr;
2678         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2679
2680         struct target *target = get_current_target(CMD_CTX);
2681         breakpoint_remove(target, addr);
2682
2683         return ERROR_OK;
2684 }
2685
2686 COMMAND_HANDLER(handle_wp_command)
2687 {
2688         struct target *target = get_current_target(CMD_CTX);
2689
2690         if (CMD_ARGC == 0)
2691         {
2692                 struct watchpoint *watchpoint = target->watchpoints;
2693
2694                 while (watchpoint)
2695                 {
2696                         command_print(CMD_CTX, "address: 0x%8.8" PRIx32
2697                                         ", len: 0x%8.8" PRIx32
2698                                         ", r/w/a: %i, value: 0x%8.8" PRIx32
2699                                         ", mask: 0x%8.8" PRIx32,
2700                                         watchpoint->address,
2701                                         watchpoint->length,
2702                                         (int)watchpoint->rw,
2703                                         watchpoint->value,
2704                                         watchpoint->mask);
2705                         watchpoint = watchpoint->next;
2706                 }
2707                 return ERROR_OK;
2708         }
2709
2710         enum watchpoint_rw type = WPT_ACCESS;
2711         uint32_t addr = 0;
2712         uint32_t length = 0;
2713         uint32_t data_value = 0x0;
2714         uint32_t data_mask = 0xffffffff;
2715
2716         switch (CMD_ARGC)
2717         {
2718         case 5:
2719                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], data_mask);
2720                 // fall through
2721         case 4:
2722                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], data_value);
2723                 // fall through
2724         case 3:
2725                 switch (CMD_ARGV[2][0])
2726                 {
2727                 case 'r':
2728                         type = WPT_READ;
2729                         break;
2730                 case 'w':
2731                         type = WPT_WRITE;
2732                         break;
2733                 case 'a':
2734                         type = WPT_ACCESS;
2735                         break;
2736                 default:
2737                         LOG_ERROR("invalid watchpoint mode ('%c')", CMD_ARGV[2][0]);
2738                         return ERROR_COMMAND_SYNTAX_ERROR;
2739                 }
2740                 // fall through
2741         case 2:
2742                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
2743                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2744                 break;
2745
2746         default:
2747                 command_print(CMD_CTX, "usage: wp [address length "
2748                                 "[(r|w|a) [value [mask]]]]");
2749                 return ERROR_COMMAND_SYNTAX_ERROR;
2750         }
2751
2752         int retval = watchpoint_add(target, addr, length, type,
2753                         data_value, data_mask);
2754         if (ERROR_OK != retval)
2755                 LOG_ERROR("Failure setting watchpoints");
2756
2757         return retval;
2758 }
2759
2760 COMMAND_HANDLER(handle_rwp_command)
2761 {
2762         if (CMD_ARGC != 1)
2763                 return ERROR_COMMAND_SYNTAX_ERROR;
2764
2765         uint32_t addr;
2766         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], addr);
2767
2768         struct target *target = get_current_target(CMD_CTX);
2769         watchpoint_remove(target, addr);
2770
2771         return ERROR_OK;
2772 }
2773
2774
2775 /**
2776  * Translate a virtual address to a physical address.
2777  *
2778  * The low-level target implementation must have logged a detailed error
2779  * which is forwarded to telnet/GDB session.
2780  */
2781 COMMAND_HANDLER(handle_virt2phys_command)
2782 {
2783         if (CMD_ARGC != 1)
2784                 return ERROR_COMMAND_SYNTAX_ERROR;
2785
2786         uint32_t va;
2787         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], va);
2788         uint32_t pa;
2789
2790         struct target *target = get_current_target(CMD_CTX);
2791         int retval = target->type->virt2phys(target, va, &pa);
2792         if (retval == ERROR_OK)
2793                 command_print(CMD_CTX, "Physical address 0x%08" PRIx32 "", pa);
2794
2795         return retval;
2796 }
2797
2798 static void writeData(FILE *f, const void *data, size_t len)
2799 {
2800         size_t written = fwrite(data, 1, len, f);
2801         if (written != len)
2802                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
2803 }
2804
2805 static void writeLong(FILE *f, int l)
2806 {
2807         int i;
2808         for (i = 0; i < 4; i++)
2809         {
2810                 char c = (l >> (i*8))&0xff;
2811                 writeData(f, &c, 1);
2812         }
2813
2814 }
2815
2816 static void writeString(FILE *f, char *s)
2817 {
2818         writeData(f, s, strlen(s));
2819 }
2820
2821 /* Dump a gmon.out histogram file. */
2822 static void writeGmon(uint32_t *samples, uint32_t sampleNum, const char *filename)
2823 {
2824         uint32_t i;
2825         FILE *f = fopen(filename, "w");
2826         if (f == NULL)
2827                 return;
2828         writeString(f, "gmon");
2829         writeLong(f, 0x00000001); /* Version */
2830         writeLong(f, 0); /* padding */
2831         writeLong(f, 0); /* padding */
2832         writeLong(f, 0); /* padding */
2833
2834         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
2835         writeData(f, &zero, 1);
2836
2837         /* figure out bucket size */
2838         uint32_t min = samples[0];
2839         uint32_t max = samples[0];
2840         for (i = 0; i < sampleNum; i++)
2841         {
2842                 if (min > samples[i])
2843                 {
2844                         min = samples[i];
2845                 }
2846                 if (max < samples[i])
2847                 {
2848                         max = samples[i];
2849                 }
2850         }
2851
2852         int addressSpace = (max-min + 1);
2853
2854         static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
2855         uint32_t length = addressSpace;
2856         if (length > maxBuckets)
2857         {
2858                 length = maxBuckets;
2859         }
2860         int *buckets = malloc(sizeof(int)*length);
2861         if (buckets == NULL)
2862         {
2863                 fclose(f);
2864                 return;
2865         }
2866         memset(buckets, 0, sizeof(int)*length);
2867         for (i = 0; i < sampleNum;i++)
2868         {
2869                 uint32_t address = samples[i];
2870                 long long a = address-min;
2871                 long long b = length-1;
2872                 long long c = addressSpace-1;
2873                 int index = (a*b)/c; /* danger!!!! int32 overflows */
2874                 buckets[index]++;
2875         }
2876
2877         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
2878         writeLong(f, min);                      /* low_pc */
2879         writeLong(f, max);                      /* high_pc */
2880         writeLong(f, length);           /* # of samples */
2881         writeLong(f, 64000000);         /* 64MHz */
2882         writeString(f, "seconds");
2883         for (i = 0; i < (15-strlen("seconds")); i++)
2884                 writeData(f, &zero, 1);
2885         writeString(f, "s");
2886
2887         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
2888
2889         char *data = malloc(2*length);
2890         if (data != NULL)
2891         {
2892                 for (i = 0; i < length;i++)
2893                 {
2894                         int val;
2895                         val = buckets[i];
2896                         if (val > 65535)
2897                         {
2898                                 val = 65535;
2899                         }
2900                         data[i*2]=val&0xff;
2901                         data[i*2 + 1]=(val >> 8)&0xff;
2902                 }
2903                 free(buckets);
2904                 writeData(f, data, length * 2);
2905                 free(data);
2906         } else
2907         {
2908                 free(buckets);
2909         }
2910
2911         fclose(f);
2912 }
2913
2914 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2915 COMMAND_HANDLER(handle_profile_command)
2916 {
2917         struct target *target = get_current_target(CMD_CTX);
2918         struct timeval timeout, now;
2919
2920         gettimeofday(&timeout, NULL);
2921         if (CMD_ARGC != 2)
2922         {
2923                 return ERROR_COMMAND_SYNTAX_ERROR;
2924         }
2925         unsigned offset;
2926         COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], offset);
2927
2928         timeval_add_time(&timeout, offset, 0);
2929
2930         command_print(CMD_CTX, "Starting profiling. Halting and resuming the target as often as we can...");
2931
2932         static const int maxSample = 10000;
2933         uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
2934         if (samples == NULL)
2935                 return ERROR_OK;
2936
2937         int numSamples = 0;
2938         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
2939         struct reg *reg = register_get_by_name(target->reg_cache, "pc", 1);
2940
2941         for (;;)
2942         {
2943                 int retval;
2944                 target_poll(target);
2945                 if (target->state == TARGET_HALTED)
2946                 {
2947                         uint32_t t=*((uint32_t *)reg->value);
2948                         samples[numSamples++]=t;
2949                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2950                         target_poll(target);
2951                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
2952                 } else if (target->state == TARGET_RUNNING)
2953                 {
2954                         /* We want to quickly sample the PC. */
2955                         if ((retval = target_halt(target)) != ERROR_OK)
2956                         {
2957                                 free(samples);
2958                                 return retval;
2959                         }
2960                 } else
2961                 {
2962                         command_print(CMD_CTX, "Target not halted or running");
2963                         retval = ERROR_OK;
2964                         break;
2965                 }
2966                 if (retval != ERROR_OK)
2967                 {
2968                         break;
2969                 }
2970
2971                 gettimeofday(&now, NULL);
2972                 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
2973                 {
2974                         command_print(CMD_CTX, "Profiling completed. %d samples.", numSamples);
2975                         if ((retval = target_poll(target)) != ERROR_OK)
2976                         {
2977                                 free(samples);
2978                                 return retval;
2979                         }
2980                         if (target->state == TARGET_HALTED)
2981                         {
2982                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2983                         }
2984                         if ((retval = target_poll(target)) != ERROR_OK)
2985                         {
2986                                 free(samples);
2987                                 return retval;
2988                         }
2989                         writeGmon(samples, numSamples, CMD_ARGV[1]);
2990                         command_print(CMD_CTX, "Wrote %s", CMD_ARGV[1]);
2991                         break;
2992                 }
2993         }
2994         free(samples);
2995
2996         return ERROR_OK;
2997 }
2998
2999 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3000 {
3001         char *namebuf;
3002         Jim_Obj *nameObjPtr, *valObjPtr;
3003         int result;
3004
3005         namebuf = alloc_printf("%s(%d)", varname, idx);
3006         if (!namebuf)
3007                 return JIM_ERR;
3008
3009         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3010         valObjPtr = Jim_NewIntObj(interp, val);
3011         if (!nameObjPtr || !valObjPtr)
3012         {
3013                 free(namebuf);
3014                 return JIM_ERR;
3015         }
3016
3017         Jim_IncrRefCount(nameObjPtr);
3018         Jim_IncrRefCount(valObjPtr);
3019         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3020         Jim_DecrRefCount(interp, nameObjPtr);
3021         Jim_DecrRefCount(interp, valObjPtr);
3022         free(namebuf);
3023         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3024         return result;
3025 }
3026
3027 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3028 {
3029         struct command_context *context;
3030         struct target *target;
3031
3032         context = Jim_GetAssocData(interp, "context");
3033         if (context == NULL)
3034         {
3035                 LOG_ERROR("mem2array: no command context");
3036                 return JIM_ERR;
3037         }
3038         target = get_current_target(context);
3039         if (target == NULL)
3040         {
3041                 LOG_ERROR("mem2array: no current target");
3042                 return JIM_ERR;
3043         }
3044
3045         return  target_mem2array(interp, target, argc-1, argv + 1);
3046 }
3047
3048 static int target_mem2array(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3049 {
3050         long l;
3051         uint32_t width;
3052         int len;
3053         uint32_t addr;
3054         uint32_t count;
3055         uint32_t v;
3056         const char *varname;
3057         int  n, e, retval;
3058         uint32_t i;
3059
3060         /* argv[1] = name of array to receive the data
3061          * argv[2] = desired width
3062          * argv[3] = memory address
3063          * argv[4] = count of times to read
3064          */
3065         if (argc != 4) {
3066                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3067                 return JIM_ERR;
3068         }
3069         varname = Jim_GetString(argv[0], &len);
3070         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3071
3072         e = Jim_GetLong(interp, argv[1], &l);
3073         width = l;
3074         if (e != JIM_OK) {
3075                 return e;
3076         }
3077
3078         e = Jim_GetLong(interp, argv[2], &l);
3079         addr = l;
3080         if (e != JIM_OK) {
3081                 return e;
3082         }
3083         e = Jim_GetLong(interp, argv[3], &l);
3084         len = l;
3085         if (e != JIM_OK) {
3086                 return e;
3087         }
3088         switch (width) {
3089                 case 8:
3090                         width = 1;
3091                         break;
3092                 case 16:
3093                         width = 2;
3094                         break;
3095                 case 32:
3096                         width = 4;
3097                         break;
3098                 default:
3099                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3100                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3101                         return JIM_ERR;
3102         }
3103         if (len == 0) {
3104                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3105                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3106                 return JIM_ERR;
3107         }
3108         if ((addr + (len * width)) < addr) {
3109                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3110                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3111                 return JIM_ERR;
3112         }
3113         /* absurd transfer size? */
3114         if (len > 65536) {
3115                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3116                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3117                 return JIM_ERR;
3118         }
3119
3120         if ((width == 1) ||
3121                 ((width == 2) && ((addr & 1) == 0)) ||
3122                 ((width == 4) && ((addr & 3) == 0))) {
3123                 /* all is well */
3124         } else {
3125                 char buf[100];
3126                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3127                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3128                                 addr,
3129                                 width);
3130                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3131                 return JIM_ERR;
3132         }
3133
3134         /* Transfer loop */
3135
3136         /* index counter */
3137         n = 0;
3138
3139         size_t buffersize = 4096;
3140         uint8_t *buffer = malloc(buffersize);
3141         if (buffer == NULL)
3142                 return JIM_ERR;
3143
3144         /* assume ok */
3145         e = JIM_OK;
3146         while (len) {
3147                 /* Slurp... in buffer size chunks */
3148
3149                 count = len; /* in objects.. */
3150                 if (count > (buffersize/width)) {
3151                         count = (buffersize/width);
3152                 }
3153
3154                 retval = target_read_memory(target, addr, width, count, buffer);
3155                 if (retval != ERROR_OK) {
3156                         /* BOO !*/
3157                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3158                                           (unsigned int)addr,
3159                                           (int)width,
3160                                           (int)count);
3161                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3162                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3163                         e = JIM_ERR;
3164                         len = 0;
3165                 } else {
3166                         v = 0; /* shut up gcc */
3167                         for (i = 0 ;i < count ;i++, n++) {
3168                                 switch (width) {
3169                                         case 4:
3170                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
3171                                                 break;
3172                                         case 2:
3173                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
3174                                                 break;
3175                                         case 1:
3176                                                 v = buffer[i] & 0x0ff;
3177                                                 break;
3178                                 }
3179                                 new_int_array_element(interp, varname, n, v);
3180                         }
3181                         len -= count;
3182                 }
3183         }
3184
3185         free(buffer);
3186
3187         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3188
3189         return JIM_OK;
3190 }
3191
3192 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3193 {
3194         char *namebuf;
3195         Jim_Obj *nameObjPtr, *valObjPtr;
3196         int result;
3197         long l;
3198
3199         namebuf = alloc_printf("%s(%d)", varname, idx);
3200         if (!namebuf)
3201                 return JIM_ERR;
3202
3203         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3204         if (!nameObjPtr)
3205         {
3206                 free(namebuf);
3207                 return JIM_ERR;
3208         }
3209
3210         Jim_IncrRefCount(nameObjPtr);
3211         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3212         Jim_DecrRefCount(interp, nameObjPtr);
3213         free(namebuf);
3214         if (valObjPtr == NULL)
3215                 return JIM_ERR;
3216
3217         result = Jim_GetLong(interp, valObjPtr, &l);
3218         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3219         *val = l;
3220         return result;
3221 }
3222
3223 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3224 {
3225         struct command_context *context;
3226         struct target *target;
3227
3228         context = Jim_GetAssocData(interp, "context");
3229         if (context == NULL) {
3230                 LOG_ERROR("array2mem: no command context");
3231                 return JIM_ERR;
3232         }
3233         target = get_current_target(context);
3234         if (target == NULL) {
3235                 LOG_ERROR("array2mem: no current target");
3236                 return JIM_ERR;
3237         }
3238
3239         return target_array2mem(interp,target, argc-1, argv + 1);
3240 }
3241 static int target_array2mem(Jim_Interp *interp, struct target *target, int argc, Jim_Obj *const *argv)
3242 {
3243         long l;
3244         uint32_t width;
3245         int len;
3246         uint32_t addr;
3247         uint32_t count;
3248         uint32_t v;
3249         const char *varname;
3250         int  n, e, retval;
3251         uint32_t i;
3252
3253         /* argv[1] = name of array to get the data
3254          * argv[2] = desired width
3255          * argv[3] = memory address
3256          * argv[4] = count to write
3257          */
3258         if (argc != 4) {
3259                 Jim_WrongNumArgs(interp, 0, argv, "varname width addr nelems");
3260                 return JIM_ERR;
3261         }
3262         varname = Jim_GetString(argv[0], &len);
3263         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3264
3265         e = Jim_GetLong(interp, argv[1], &l);
3266         width = l;
3267         if (e != JIM_OK) {
3268                 return e;
3269         }
3270
3271         e = Jim_GetLong(interp, argv[2], &l);
3272         addr = l;
3273         if (e != JIM_OK) {
3274                 return e;
3275         }
3276         e = Jim_GetLong(interp, argv[3], &l);
3277         len = l;
3278         if (e != JIM_OK) {
3279                 return e;
3280         }
3281         switch (width) {
3282                 case 8:
3283                         width = 1;
3284                         break;
3285                 case 16:
3286                         width = 2;
3287                         break;
3288                 case 32:
3289                         width = 4;
3290                         break;
3291                 default:
3292                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3293                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3294                         return JIM_ERR;
3295         }
3296         if (len == 0) {
3297                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3298                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3299                 return JIM_ERR;
3300         }
3301         if ((addr + (len * width)) < addr) {
3302                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3303                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3304                 return JIM_ERR;
3305         }
3306         /* absurd transfer size? */
3307         if (len > 65536) {
3308                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3309                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3310                 return JIM_ERR;
3311         }
3312
3313         if ((width == 1) ||
3314                 ((width == 2) && ((addr & 1) == 0)) ||
3315                 ((width == 4) && ((addr & 3) == 0))) {
3316                 /* all is well */
3317         } else {
3318                 char buf[100];
3319                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3320                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3321                                 (unsigned int)addr,
3322                                 (int)width);
3323                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3324                 return JIM_ERR;
3325         }
3326
3327         /* Transfer loop */
3328
3329         /* index counter */
3330         n = 0;
3331         /* assume ok */
3332         e = JIM_OK;
3333
3334         size_t buffersize = 4096;
3335         uint8_t *buffer = malloc(buffersize);
3336         if (buffer == NULL)
3337                 return JIM_ERR;
3338
3339         while (len) {
3340                 /* Slurp... in buffer size chunks */
3341
3342                 count = len; /* in objects.. */
3343                 if (count > (buffersize/width)) {
3344                         count = (buffersize/width);
3345                 }
3346
3347                 v = 0; /* shut up gcc */
3348                 for (i = 0 ;i < count ;i++, n++) {
3349                         get_int_array_element(interp, varname, n, &v);
3350                         switch (width) {
3351                         case 4:
3352                                 target_buffer_set_u32(target, &buffer[i*width], v);
3353                                 break;
3354                         case 2:
3355                                 target_buffer_set_u16(target, &buffer[i*width], v);
3356                                 break;
3357                         case 1:
3358                                 buffer[i] = v & 0x0ff;
3359                                 break;
3360                         }
3361                 }
3362                 len -= count;
3363
3364                 retval = target_write_memory(target, addr, width, count, buffer);
3365                 if (retval != ERROR_OK) {
3366                         /* BOO !*/
3367                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3368                                           (unsigned int)addr,
3369                                           (int)width,
3370                                           (int)count);
3371                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3372                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3373                         e = JIM_ERR;
3374                         len = 0;
3375                 }
3376         }
3377
3378         free(buffer);
3379
3380         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3381
3382         return JIM_OK;
3383 }
3384
3385 void target_all_handle_event(enum target_event e)
3386 {
3387         struct target *target;
3388
3389         LOG_DEBUG("**all*targets: event: %d, %s",
3390                            (int)e,
3391                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3392
3393         target = all_targets;
3394         while (target) {
3395                 target_handle_event(target, e);
3396                 target = target->next;
3397         }
3398 }
3399
3400
3401 /* FIX? should we propagate errors here rather than printing them
3402  * and continuing?
3403  */
3404 void target_handle_event(struct target *target, enum target_event e)
3405 {
3406         struct target_event_action *teap;
3407
3408         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3409                 if (teap->event == e) {
3410                         LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3411                                            target->target_number,
3412                                            target_name(target),
3413                                            target_type_name(target),
3414                                            e,
3415                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3416                                            Jim_GetString(teap->body, NULL));
3417                         if (Jim_EvalObj(teap->interp, teap->body) != JIM_OK)
3418                         {
3419                                 Jim_PrintErrorMessage(teap->interp);
3420                         }
3421                 }
3422         }
3423 }
3424
3425 /**
3426  * Returns true only if the target has a handler for the specified event.
3427  */
3428 bool target_has_event_action(struct target *target, enum target_event event)
3429 {
3430         struct target_event_action *teap;
3431
3432         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3433                 if (teap->event == event)
3434                         return true;
3435         }
3436         return false;
3437 }
3438
3439 enum target_cfg_param {
3440         TCFG_TYPE,
3441         TCFG_EVENT,
3442         TCFG_WORK_AREA_VIRT,
3443         TCFG_WORK_AREA_PHYS,
3444         TCFG_WORK_AREA_SIZE,
3445         TCFG_WORK_AREA_BACKUP,
3446         TCFG_ENDIAN,
3447         TCFG_VARIANT,
3448         TCFG_CHAIN_POSITION,
3449 };
3450
3451 static Jim_Nvp nvp_config_opts[] = {
3452         { .name = "-type",             .value = TCFG_TYPE },
3453         { .name = "-event",            .value = TCFG_EVENT },
3454         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
3455         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
3456         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
3457         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3458         { .name = "-endian" ,          .value = TCFG_ENDIAN },
3459         { .name = "-variant",          .value = TCFG_VARIANT },
3460         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
3461
3462         { .name = NULL, .value = -1 }
3463 };
3464
3465 static int target_configure(Jim_GetOptInfo *goi, struct target *target)
3466 {
3467         Jim_Nvp *n;
3468         Jim_Obj *o;
3469         jim_wide w;
3470         char *cp;
3471         int e;
3472
3473         /* parse config or cget options ... */
3474         while (goi->argc > 0) {
3475                 Jim_SetEmptyResult(goi->interp);
3476                 /* Jim_GetOpt_Debug(goi); */
3477
3478                 if (target->type->target_jim_configure) {
3479                         /* target defines a configure function */
3480                         /* target gets first dibs on parameters */
3481                         e = (*(target->type->target_jim_configure))(target, goi);
3482                         if (e == JIM_OK) {
3483                                 /* more? */
3484                                 continue;
3485                         }
3486                         if (e == JIM_ERR) {
3487                                 /* An error */
3488                                 return e;
3489                         }
3490                         /* otherwise we 'continue' below */
3491                 }
3492                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3493                 if (e != JIM_OK) {
3494                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3495                         return e;
3496                 }
3497                 switch (n->value) {
3498                 case TCFG_TYPE:
3499                         /* not setable */
3500                         if (goi->isconfigure) {
3501                                 Jim_SetResult_sprintf(goi->interp,
3502                                                 "not settable: %s", n->name);
3503                                 return JIM_ERR;
3504                         } else {
3505                         no_params:
3506                                 if (goi->argc != 0) {
3507                                         Jim_WrongNumArgs(goi->interp,
3508                                                         goi->argc, goi->argv,
3509                                                         "NO PARAMS");
3510                                         return JIM_ERR;
3511                                 }
3512                         }
3513                         Jim_SetResultString(goi->interp,
3514                                         target_type_name(target), -1);
3515                         /* loop for more */
3516                         break;
3517                 case TCFG_EVENT:
3518                         if (goi->argc == 0) {
3519                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3520                                 return JIM_ERR;
3521                         }
3522
3523                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3524                         if (e != JIM_OK) {
3525                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3526                                 return e;
3527                         }
3528
3529                         if (goi->isconfigure) {
3530                                 if (goi->argc != 1) {
3531                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3532                                         return JIM_ERR;
3533                                 }
3534                         } else {
3535                                 if (goi->argc != 0) {
3536                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3537                                         return JIM_ERR;
3538                                 }
3539                         }
3540
3541                         {
3542                                 struct target_event_action *teap;
3543
3544                                 teap = target->event_action;
3545                                 /* replace existing? */
3546                                 while (teap) {
3547                                         if (teap->event == (enum target_event)n->value) {
3548                                                 break;
3549                                         }
3550                                         teap = teap->next;
3551                                 }
3552
3553                                 if (goi->isconfigure) {
3554                                         bool replace = true;
3555                                         if (teap == NULL) {
3556                                                 /* create new */
3557                                                 teap = calloc(1, sizeof(*teap));
3558                                                 replace = false;
3559                                         }
3560                                         teap->event = n->value;
3561                                         teap->interp = goi->interp;
3562                                         Jim_GetOpt_Obj(goi, &o);
3563                                         if (teap->body) {
3564                                                 Jim_DecrRefCount(teap->interp, teap->body);
3565                                         }
3566                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
3567                                         /*
3568                                          * FIXME:
3569                                          *     Tcl/TK - "tk events" have a nice feature.
3570                                          *     See the "BIND" command.
3571                                          *    We should support that here.
3572                                          *     You can specify %X and %Y in the event code.
3573                                          *     The idea is: %T - target name.
3574                                          *     The idea is: %N - target number
3575                                          *     The idea is: %E - event name.
3576                                          */
3577                                         Jim_IncrRefCount(teap->body);
3578
3579                                         if (!replace)
3580                                         {
3581                                                 /* add to head of event list */
3582                                                 teap->next = target->event_action;
3583                                                 target->event_action = teap;
3584                                         }
3585                                         Jim_SetEmptyResult(goi->interp);
3586                                 } else {
3587                                         /* get */
3588                                         if (teap == NULL) {
3589                                                 Jim_SetEmptyResult(goi->interp);
3590                                         } else {
3591                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3592                                         }
3593                                 }
3594                         }
3595                         /* loop for more */
3596                         break;
3597
3598                 case TCFG_WORK_AREA_VIRT:
3599                         if (goi->isconfigure) {
3600                                 target_free_all_working_areas(target);
3601                                 e = Jim_GetOpt_Wide(goi, &w);
3602                                 if (e != JIM_OK) {
3603                                         return e;
3604                                 }
3605                                 target->working_area_virt = w;
3606                                 target->working_area_virt_spec = true;
3607                         } else {
3608                                 if (goi->argc != 0) {
3609                                         goto no_params;
3610                                 }
3611                         }
3612                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3613                         /* loop for more */
3614                         break;
3615
3616                 case TCFG_WORK_AREA_PHYS:
3617                         if (goi->isconfigure) {
3618                                 target_free_all_working_areas(target);
3619                                 e = Jim_GetOpt_Wide(goi, &w);
3620                                 if (e != JIM_OK) {
3621                                         return e;
3622                                 }
3623                                 target->working_area_phys = w;
3624                                 target->working_area_phys_spec = true;
3625                         } else {
3626                                 if (goi->argc != 0) {
3627                                         goto no_params;
3628                                 }
3629                         }
3630                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3631                         /* loop for more */
3632                         break;
3633
3634                 case TCFG_WORK_AREA_SIZE:
3635                         if (goi->isconfigure) {
3636                                 target_free_all_working_areas(target);
3637                                 e = Jim_GetOpt_Wide(goi, &w);
3638                                 if (e != JIM_OK) {
3639                                         return e;
3640                                 }
3641                                 target->working_area_size = w;
3642                         } else {
3643                                 if (goi->argc != 0) {
3644                                         goto no_params;
3645                                 }
3646                         }
3647                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3648                         /* loop for more */
3649                         break;
3650
3651                 case TCFG_WORK_AREA_BACKUP:
3652                         if (goi->isconfigure) {
3653                                 target_free_all_working_areas(target);
3654                                 e = Jim_GetOpt_Wide(goi, &w);
3655                                 if (e != JIM_OK) {
3656                                         return e;
3657                                 }
3658                                 /* make this exactly 1 or 0 */
3659                                 target->backup_working_area = (!!w);
3660                         } else {
3661                                 if (goi->argc != 0) {
3662                                         goto no_params;
3663                                 }
3664                         }
3665                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3666                         /* loop for more e*/
3667                         break;
3668
3669                 case TCFG_ENDIAN:
3670                         if (goi->isconfigure) {
3671                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3672                                 if (e != JIM_OK) {
3673                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3674                                         return e;
3675                                 }
3676                                 target->endianness = n->value;
3677                         } else {
3678                                 if (goi->argc != 0) {
3679                                         goto no_params;
3680                                 }
3681                         }
3682                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3683                         if (n->name == NULL) {
3684                                 target->endianness = TARGET_LITTLE_ENDIAN;
3685                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3686                         }
3687                         Jim_SetResultString(goi->interp, n->name, -1);
3688                         /* loop for more */
3689                         break;
3690
3691                 case TCFG_VARIANT:
3692                         if (goi->isconfigure) {
3693                                 if (goi->argc < 1) {
3694                                         Jim_SetResult_sprintf(goi->interp,
3695                                                                                    "%s ?STRING?",
3696                                                                                    n->name);
3697                                         return JIM_ERR;
3698                                 }
3699                                 if (target->variant) {
3700                                         free((void *)(target->variant));
3701                                 }
3702                                 e = Jim_GetOpt_String(goi, &cp, NULL);
3703                                 target->variant = strdup(cp);
3704                         } else {
3705                                 if (goi->argc != 0) {
3706                                         goto no_params;
3707                                 }
3708                         }
3709                         Jim_SetResultString(goi->interp, target->variant,-1);
3710                         /* loop for more */
3711                         break;
3712                 case TCFG_CHAIN_POSITION:
3713                         if (goi->isconfigure) {
3714                                 Jim_Obj *o;
3715                                 struct jtag_tap *tap;
3716                                 target_free_all_working_areas(target);
3717                                 e = Jim_GetOpt_Obj(goi, &o);
3718                                 if (e != JIM_OK) {
3719                                         return e;
3720                                 }
3721                                 tap = jtag_tap_by_jim_obj(goi->interp, o);
3722                                 if (tap == NULL) {
3723                                         return JIM_ERR;
3724                                 }
3725                                 /* make this exactly 1 or 0 */
3726                                 target->tap = tap;
3727                         } else {
3728                                 if (goi->argc != 0) {
3729                                         goto no_params;
3730                                 }
3731                         }
3732                         Jim_SetResultString(goi->interp, target->tap->dotted_name, -1);
3733                         /* loop for more e*/
3734                         break;
3735                 }
3736         } /* while (goi->argc) */
3737
3738
3739                 /* done - we return */
3740         return JIM_OK;
3741 }
3742
3743 static int jim_target_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3744 {
3745         Jim_GetOptInfo goi;
3746         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3747         goi.isconfigure = strcmp(Jim_GetString(argv[0], NULL), "configure") == 0;
3748         int need_args = 1 + goi.isconfigure;
3749         if (goi.argc < need_args)
3750         {
3751                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
3752                         goi.isconfigure
3753                                 ? "missing: -option VALUE ..."
3754                                 : "missing: -option ...");
3755                 return JIM_ERR;
3756         }
3757         struct target *target = Jim_CmdPrivData(goi.interp);
3758         return target_configure(&goi, target);
3759 }
3760
3761 static int jim_target_mw(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3762 {
3763         const char *cmd_name = Jim_GetString(argv[0], NULL);
3764
3765         Jim_GetOptInfo goi;
3766         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3767
3768         if (goi.argc != 2 && goi.argc != 3)
3769         {
3770                 Jim_SetResult_sprintf(goi.interp,
3771                                 "usage: %s <address> <data> [<count>]", cmd_name);
3772                 return JIM_ERR;
3773         }
3774
3775         jim_wide a;
3776         int e = Jim_GetOpt_Wide(&goi, &a);
3777         if (e != JIM_OK)
3778                 return e;
3779
3780         jim_wide b;
3781         e = Jim_GetOpt_Wide(&goi, &b);
3782         if (e != JIM_OK)
3783                 return e;
3784
3785         jim_wide c = 1;
3786         if (goi.argc == 3)
3787         {
3788                 e = Jim_GetOpt_Wide(&goi, &c);
3789                 if (e != JIM_OK)
3790                         return e;
3791         }
3792
3793         struct target *target = Jim_CmdPrivData(goi.interp);
3794         uint8_t  target_buf[32];
3795         if (strcasecmp(cmd_name, "mww") == 0) {
3796                 target_buffer_set_u32(target, target_buf, b);
3797                 b = 4;
3798         }
3799         else if (strcasecmp(cmd_name, "mwh") == 0) {
3800                 target_buffer_set_u16(target, target_buf, b);
3801                 b = 2;
3802         }
3803         else if (strcasecmp(cmd_name, "mwb") == 0) {
3804                 target_buffer_set_u8(target, target_buf, b);
3805                 b = 1;
3806         } else {
3807                 LOG_ERROR("command '%s' unknown: ", cmd_name);
3808                 return JIM_ERR;
3809         }
3810
3811         for (jim_wide x = 0; x < c; x++)
3812         {
3813                 e = target_write_memory(target, a, b, 1, target_buf);
3814                 if (e != ERROR_OK)
3815                 {
3816                         Jim_SetResult_sprintf(interp,
3817                                         "Error writing @ 0x%08x: %d\n", (int)(a), e);
3818                         return JIM_ERR;
3819                 }
3820                 /* b = width */
3821                 a = a + b;
3822         }
3823         return JIM_OK;
3824 }
3825
3826 static int jim_target_md(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3827 {
3828         const char *cmd_name = Jim_GetString(argv[0], NULL);
3829
3830         Jim_GetOptInfo goi;
3831         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
3832
3833         if ((goi.argc == 2) || (goi.argc == 3))
3834         {
3835                 Jim_SetResult_sprintf(goi.interp,
3836                                 "usage: %s <address> [<count>]", cmd_name);
3837                 return JIM_ERR;
3838         }
3839
3840         jim_wide a;
3841         int e = Jim_GetOpt_Wide(&goi, &a);
3842         if (e != JIM_OK) {
3843                 return JIM_ERR;
3844         }
3845         jim_wide c;
3846         if (goi.argc) {
3847                 e = Jim_GetOpt_Wide(&goi, &c);
3848                 if (e != JIM_OK) {
3849                         return JIM_ERR;
3850                 }
3851         } else {
3852                 c = 1;
3853         }
3854         jim_wide b = 1; /* shut up gcc */
3855         if (strcasecmp(cmd_name, "mdw") == 0)
3856                 b = 4;
3857         else if (strcasecmp(cmd_name, "mdh") == 0)
3858                 b = 2;
3859         else if (strcasecmp(cmd_name, "mdb") == 0)
3860                 b = 1;
3861         else {
3862                 LOG_ERROR("command '%s' unknown: ", cmd_name);
3863                 return JIM_ERR;
3864         }
3865
3866         /* convert count to "bytes" */
3867         c = c * b;
3868
3869         struct target *target = Jim_CmdPrivData(goi.interp);
3870         uint8_t  target_buf[32];
3871         jim_wide x, y, z;
3872         while (c > 0) {
3873                 y = c;
3874                 if (y > 16) {
3875                         y = 16;
3876                 }
3877                 e = target_read_memory(target, a, b, y / b, target_buf);
3878                 if (e != ERROR_OK) {
3879                         Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
3880                         return JIM_ERR;
3881                 }
3882
3883                 Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
3884                 switch (b) {
3885                 case 4:
3886                         for (x = 0; x < 16 && x < y; x += 4)
3887                         {
3888                                 z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
3889                                 Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
3890                         }
3891                         for (; (x < 16) ; x += 4) {
3892                                 Jim_fprintf(interp, interp->cookie_stdout, "         ");
3893                         }
3894                         break;
3895                 case 2:
3896                         for (x = 0; x < 16 && x < y; x += 2)
3897                         {
3898                                 z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
3899                                 Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
3900                         }
3901                         for (; (x < 16) ; x += 2) {
3902                                 Jim_fprintf(interp, interp->cookie_stdout, "     ");
3903                         }
3904                         break;
3905                 case 1:
3906                 default:
3907                         for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
3908                                 z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
3909                                 Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
3910                         }
3911                         for (; (x < 16) ; x += 1) {
3912                                 Jim_fprintf(interp, interp->cookie_stdout, "   ");
3913                         }
3914                         break;
3915                 }
3916                 /* ascii-ify the bytes */
3917                 for (x = 0 ; x < y ; x++) {
3918                         if ((target_buf[x] >= 0x20) &&
3919                                 (target_buf[x] <= 0x7e)) {
3920                                 /* good */
3921                         } else {
3922                                 /* smack it */
3923                                 target_buf[x] = '.';
3924                         }
3925                 }
3926                 /* space pad  */
3927                 while (x < 16) {
3928                         target_buf[x] = ' ';
3929                         x++;
3930                 }
3931                 /* terminate */
3932                 target_buf[16] = 0;
3933                 /* print - with a newline */
3934                 Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
3935                 /* NEXT... */
3936                 c -= 16;
3937                 a += 16;
3938         }
3939         return JIM_OK;
3940 }
3941
3942 static int jim_target_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3943 {
3944         struct target *target = Jim_CmdPrivData(interp);
3945         return target_mem2array(interp, target, argc - 1, argv + 1);
3946 }
3947
3948 static int jim_target_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3949 {
3950         struct target *target = Jim_CmdPrivData(interp);
3951         return target_array2mem(interp, target, argc - 1, argv + 1);
3952 }
3953
3954 static int jim_target_tap_disabled(Jim_Interp *interp)
3955 {
3956         Jim_SetResult_sprintf(interp, "[TAP is disabled]");
3957         return JIM_ERR;
3958 }
3959
3960 static int jim_target_examine(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3961 {
3962         if (argc != 1)
3963         {
3964                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
3965                 return JIM_ERR;
3966         }
3967         struct target *target = Jim_CmdPrivData(interp);
3968         if (!target->tap->enabled)
3969                 return jim_target_tap_disabled(interp);
3970
3971         int e = target->type->examine(target);
3972         if (e != ERROR_OK)
3973         {
3974                 Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
3975                 return JIM_ERR;
3976         }
3977         return JIM_OK;
3978 }
3979
3980 static int jim_target_poll(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3981 {
3982         if (argc != 1)
3983         {
3984                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
3985                 return JIM_ERR;
3986         }
3987         struct target *target = Jim_CmdPrivData(interp);
3988         if (!target->tap->enabled)
3989                 return jim_target_tap_disabled(interp);
3990
3991         int e;
3992         if (!(target_was_examined(target))) {
3993                 e = ERROR_TARGET_NOT_EXAMINED;
3994         } else {
3995                 e = target->type->poll(target);
3996         }
3997         if (e != ERROR_OK)
3998         {
3999                 Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4000                 return JIM_ERR;
4001         }
4002         return JIM_OK;
4003 }
4004
4005 static int jim_target_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4006 {
4007         Jim_GetOptInfo goi;
4008         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4009
4010         if (goi.argc != 2)
4011         {
4012                 Jim_WrongNumArgs(interp, 0, argv,
4013                                 "([tT]|[fF]|assert|deassert) BOOL");
4014                 return JIM_ERR;
4015         }
4016
4017         Jim_Nvp *n;
4018         int e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4019         if (e != JIM_OK)
4020         {
4021                 Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4022                 return e;
4023         }
4024         /* the halt or not param */
4025         jim_wide a;
4026         e = Jim_GetOpt_Wide(&goi, &a);
4027         if (e != JIM_OK)
4028                 return e;
4029
4030         struct target *target = Jim_CmdPrivData(goi.interp);
4031         if (!target->tap->enabled)
4032                 return jim_target_tap_disabled(interp);
4033         if (!target->type->assert_reset || !target->type->deassert_reset)
4034         {
4035                 Jim_SetResult_sprintf(interp,
4036                                 "No target-specific reset for %s",
4037                                 target_name(target));
4038                 return JIM_ERR;
4039         }
4040         /* determine if we should halt or not. */
4041         target->reset_halt = !!a;
4042         /* When this happens - all workareas are invalid. */
4043         target_free_all_working_areas_restore(target, 0);
4044
4045         /* do the assert */
4046         if (n->value == NVP_ASSERT) {
4047                 e = target->type->assert_reset(target);
4048         } else {
4049                 e = target->type->deassert_reset(target);
4050         }
4051         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4052 }
4053
4054 static int jim_target_halt(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4055 {
4056         if (argc != 1) {
4057                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4058                 return JIM_ERR;
4059         }
4060         struct target *target = Jim_CmdPrivData(interp);
4061         if (!target->tap->enabled)
4062                 return jim_target_tap_disabled(interp);
4063         int e = target->type->halt(target);
4064         return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4065 }
4066
4067 static int jim_target_wait_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4068 {
4069         Jim_GetOptInfo goi;
4070         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4071
4072         /* params:  <name>  statename timeoutmsecs */
4073         if (goi.argc != 2)
4074         {
4075                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4076                 Jim_SetResult_sprintf(goi.interp,
4077                                 "%s <state_name> <timeout_in_msec>", cmd_name);
4078                 return JIM_ERR;
4079         }
4080
4081         Jim_Nvp *n;
4082         int e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4083         if (e != JIM_OK) {
4084                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4085                 return e;
4086         }
4087         jim_wide a;
4088         e = Jim_GetOpt_Wide(&goi, &a);
4089         if (e != JIM_OK) {
4090                 return e;
4091         }
4092         struct target *target = Jim_CmdPrivData(interp);
4093         if (!target->tap->enabled)
4094                 return jim_target_tap_disabled(interp);
4095
4096         e = target_wait_state(target, n->value, a);
4097         if (e != ERROR_OK)
4098         {
4099                 Jim_SetResult_sprintf(goi.interp,
4100                                 "target: %s wait %s fails (%d) %s",
4101                                 target_name(target), n->name,
4102                                 e, target_strerror_safe(e));
4103                 return JIM_ERR;
4104         }
4105         return JIM_OK;
4106 }
4107 /* List for human, Events defined for this target.
4108  * scripts/programs should use 'name cget -event NAME'
4109  */
4110 static int jim_target_event_list(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4111 {
4112         struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
4113         struct target *target = Jim_CmdPrivData(interp);
4114         struct target_event_action *teap = target->event_action;
4115         command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4116                                    target->target_number,
4117                                    target_name(target));
4118         command_print(cmd_ctx, "%-25s | Body", "Event");
4119         command_print(cmd_ctx, "------------------------- | "
4120                         "----------------------------------------");
4121         while (teap)
4122         {
4123                 Jim_Nvp *opt = Jim_Nvp_value2name_simple(nvp_target_event, teap->event);
4124                 command_print(cmd_ctx, "%-25s | %s",
4125                                 opt->name, Jim_GetString(teap->body, NULL));
4126                 teap = teap->next;
4127         }
4128         command_print(cmd_ctx, "***END***");
4129         return JIM_OK;
4130 }
4131 static int jim_target_current_state(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4132 {
4133         if (argc != 1)
4134         {
4135                 Jim_WrongNumArgs(interp, 1, argv, "[no parameters]");
4136                 return JIM_ERR;
4137         }
4138         struct target *target = Jim_CmdPrivData(interp);
4139         Jim_SetResultString(interp, target_state_name(target), -1);
4140         return JIM_OK;
4141 }
4142 static int jim_target_invoke_event(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4143 {
4144         Jim_GetOptInfo goi;
4145         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4146         if (goi.argc != 1)
4147         {
4148                 const char *cmd_name = Jim_GetString(argv[0], NULL);
4149                 Jim_SetResult_sprintf(goi.interp, "%s <eventname>", cmd_name);
4150                 return JIM_ERR;
4151         }
4152         Jim_Nvp *n;
4153         int e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4154         if (e != JIM_OK)
4155         {
4156                 Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4157                 return e;
4158         }
4159         struct target *target = Jim_CmdPrivData(interp);
4160         target_handle_event(target, n->value);
4161         return JIM_OK;
4162 }
4163
4164 static const struct command_registration target_instance_command_handlers[] = {
4165         {
4166                 .name = "configure",
4167                 .mode = COMMAND_CONFIG,
4168                 .jim_handler = &jim_target_configure,
4169                 .usage = "[<target_options> ...]",
4170                 .help  = "configure a new target for use",
4171         },
4172         {
4173                 .name = "cget",
4174                 .mode = COMMAND_ANY,
4175                 .jim_handler = &jim_target_configure,
4176                 .usage = "<target_type> [<target_options> ...]",
4177                 .help  = "configure a new target for use",
4178         },
4179         {
4180                 .name = "mww",
4181                 .mode = COMMAND_EXEC,
4182                 .jim_handler = &jim_target_mw,
4183                 .usage = "<address> <data> [<count>]",
4184                 .help = "Write 32-bit word(s) to target memory",
4185         },
4186         {
4187                 .name = "mwh",
4188                 .mode = COMMAND_EXEC,
4189                 .jim_handler = &jim_target_mw,
4190                 .usage = "<address> <data> [<count>]",
4191                 .help = "Write 16-bit half-word(s) to target memory",
4192         },
4193         {
4194                 .name = "mwb",
4195                 .mode = COMMAND_EXEC,
4196                 .jim_handler = &jim_target_mw,
4197                 .usage = "<address> <data> [<count>]",
4198                 .help = "Write byte(s) to target memory",
4199         },
4200         {
4201                 .name = "mdw",
4202                 .mode = COMMAND_EXEC,
4203                 .jim_handler = &jim_target_md,
4204                 .usage = "<address> [<count>]",
4205                 .help = "Display target memory as 32-bit words",
4206         },
4207         {
4208                 .name = "mdh",
4209                 .mode = COMMAND_EXEC,
4210                 .jim_handler = &jim_target_md,
4211                 .usage = "<address> [<count>]",
4212                 .help = "Display target memory as 16-bit half-words",
4213         },
4214         {
4215                 .name = "mdb",
4216                 .mode = COMMAND_EXEC,
4217                 .jim_handler = &jim_target_md,
4218                 .usage = "<address> [<count>]",
4219                 .help = "Display target memory as 8-bit bytes",
4220         },
4221         {
4222                 .name = "array2mem",
4223                 .mode = COMMAND_EXEC,
4224                 .jim_handler = &jim_target_array2mem,
4225         },
4226         {
4227                 .name = "mem2array",
4228                 .mode = COMMAND_EXEC,
4229                 .jim_handler = &jim_target_mem2array,
4230         },
4231         {
4232                 .name = "eventlist",
4233                 .mode = COMMAND_EXEC,
4234                 .jim_handler = &jim_target_event_list,
4235         },
4236         {
4237                 .name = "curstate",
4238                 .mode = COMMAND_EXEC,
4239                 .jim_handler = &jim_target_current_state,
4240         },
4241         {
4242                 .name = "arp_examine",
4243                 .mode = COMMAND_EXEC,
4244                 .jim_handler = &jim_target_examine,
4245         },
4246         {
4247                 .name = "arp_poll",
4248                 .mode = COMMAND_EXEC,
4249                 .jim_handler = &jim_target_poll,
4250         },
4251         {
4252                 .name = "arp_reset",
4253                 .mode = COMMAND_EXEC,
4254                 .jim_handler = &jim_target_reset,
4255         },
4256         {
4257                 .name = "arp_halt",
4258                 .mode = COMMAND_EXEC,
4259                 .jim_handler = &jim_target_halt,
4260         },
4261         {
4262                 .name = "arp_waitstate",
4263                 .mode = COMMAND_EXEC,
4264                 .jim_handler = &jim_target_wait_state,
4265         },
4266         {
4267                 .name = "invoke-event",
4268                 .mode = COMMAND_EXEC,
4269                 .jim_handler = &jim_target_invoke_event,
4270         },
4271         COMMAND_REGISTRATION_DONE
4272 };
4273
4274 static int target_create(Jim_GetOptInfo *goi)
4275 {
4276         Jim_Obj *new_cmd;
4277         Jim_Cmd *cmd;
4278         const char *cp;
4279         char *cp2;
4280         int e;
4281         int x;
4282         struct target *target;
4283         struct command_context *cmd_ctx;
4284
4285         cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4286         if (goi->argc < 3) {
4287                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4288                 return JIM_ERR;
4289         }
4290
4291         /* COMMAND */
4292         Jim_GetOpt_Obj(goi, &new_cmd);
4293         /* does this command exist? */
4294         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4295         if (cmd) {
4296                 cp = Jim_GetString(new_cmd, NULL);
4297                 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4298                 return JIM_ERR;
4299         }
4300
4301         /* TYPE */
4302         e = Jim_GetOpt_String(goi, &cp2, NULL);
4303         cp = cp2;
4304         /* now does target type exist */
4305         for (x = 0 ; target_types[x] ; x++) {
4306                 if (0 == strcmp(cp, target_types[x]->name)) {
4307                         /* found */
4308                         break;
4309                 }
4310         }
4311         if (target_types[x] == NULL) {
4312                 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4313                 for (x = 0 ; target_types[x] ; x++) {
4314                         if (target_types[x + 1]) {
4315                                 Jim_AppendStrings(goi->interp,
4316                                                                    Jim_GetResult(goi->interp),
4317                                                                    target_types[x]->name,
4318                                                                    ", ", NULL);
4319                         } else {
4320                                 Jim_AppendStrings(goi->interp,
4321                                                                    Jim_GetResult(goi->interp),
4322                                                                    " or ",
4323                                                                    target_types[x]->name,NULL);
4324                         }
4325                 }
4326                 return JIM_ERR;
4327         }
4328
4329         /* Create it */
4330         target = calloc(1,sizeof(struct target));
4331         /* set target number */
4332         target->target_number = new_target_number();
4333
4334         /* allocate memory for each unique target type */
4335         target->type = (struct target_type*)calloc(1,sizeof(struct target_type));
4336
4337         memcpy(target->type, target_types[x], sizeof(struct target_type));
4338
4339         /* will be set by "-endian" */
4340         target->endianness = TARGET_ENDIAN_UNKNOWN;
4341
4342         target->working_area        = 0x0;
4343         target->working_area_size   = 0x0;
4344         target->working_areas       = NULL;
4345         target->backup_working_area = 0;
4346
4347         target->state               = TARGET_UNKNOWN;
4348         target->debug_reason        = DBG_REASON_UNDEFINED;
4349         target->reg_cache           = NULL;
4350         target->breakpoints         = NULL;
4351         target->watchpoints         = NULL;
4352         target->next                = NULL;
4353         target->arch_info           = NULL;
4354
4355         target->display             = 1;
4356
4357         target->halt_issued                     = false;
4358
4359         /* initialize trace information */
4360         target->trace_info = malloc(sizeof(struct trace));
4361         target->trace_info->num_trace_points         = 0;
4362         target->trace_info->trace_points_size        = 0;
4363         target->trace_info->trace_points             = NULL;
4364         target->trace_info->trace_history_size       = 0;
4365         target->trace_info->trace_history            = NULL;
4366         target->trace_info->trace_history_pos        = 0;
4367         target->trace_info->trace_history_overflowed = 0;
4368
4369         target->dbgmsg          = NULL;
4370         target->dbg_msg_enabled = 0;
4371
4372         target->endianness = TARGET_ENDIAN_UNKNOWN;
4373
4374         /* Do the rest as "configure" options */
4375         goi->isconfigure = 1;
4376         e = target_configure(goi, target);
4377
4378         if (target->tap == NULL)
4379         {
4380                 Jim_SetResultString(goi->interp, "-chain-position required when creating target", -1);
4381                 e = JIM_ERR;
4382         }
4383
4384         if (e != JIM_OK) {
4385                 free(target->type);
4386                 free(target);
4387                 return e;
4388         }
4389
4390         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4391                 /* default endian to little if not specified */
4392                 target->endianness = TARGET_LITTLE_ENDIAN;
4393         }
4394
4395         /* incase variant is not set */
4396         if (!target->variant)
4397                 target->variant = strdup("");
4398
4399         cp = Jim_GetString(new_cmd, NULL);
4400         target->cmd_name = strdup(cp);
4401
4402         /* create the target specific commands */
4403         if (target->type->commands) {
4404                 e = register_commands(cmd_ctx, NULL, target->type->commands);
4405                 if (ERROR_OK != e)
4406                         LOG_ERROR("unable to register '%s' commands", cp);
4407         }
4408         if (target->type->target_create) {
4409                 (*(target->type->target_create))(target, goi->interp);
4410         }
4411
4412         /* append to end of list */
4413         {
4414                 struct target **tpp;
4415                 tpp = &(all_targets);
4416                 while (*tpp) {
4417                         tpp = &((*tpp)->next);
4418                 }
4419                 *tpp = target;
4420         }
4421         
4422         /* now - create the new target name command */
4423         const const struct command_registration target_subcommands[] = {
4424                 {
4425                         .chain = target_instance_command_handlers,
4426                 },
4427                 {
4428                         .chain = target->type->commands,
4429                 },
4430                 COMMAND_REGISTRATION_DONE
4431         };
4432         const const struct command_registration target_commands[] = {
4433                 {
4434                         .name = cp,
4435                         .mode = COMMAND_ANY,
4436                         .help = "target command group",
4437                         .chain = target_subcommands,
4438                 },
4439                 COMMAND_REGISTRATION_DONE
4440         };
4441         e = register_commands(cmd_ctx, NULL, target_commands);
4442         if (ERROR_OK != e)
4443                 return JIM_ERR;
4444
4445         struct command *c = command_find_in_context(cmd_ctx, cp);
4446         assert(c);
4447         command_set_handler_data(c, target);
4448
4449         return (ERROR_OK == e) ? JIM_OK : JIM_ERR;
4450 }
4451
4452 static int jim_target_current(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4453 {
4454         if (argc != 1)
4455         {
4456                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4457                 return JIM_ERR;
4458         }
4459         struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
4460         Jim_SetResultString(interp, get_current_target(cmd_ctx)->cmd_name, -1);
4461         return JIM_OK;
4462 }
4463
4464 static int jim_target_types(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4465 {
4466         if (argc != 1)
4467         {
4468                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4469                 return JIM_ERR;
4470         }
4471         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4472         for (unsigned x = 0; NULL != target_types[x]; x++)
4473         {
4474                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4475                         Jim_NewStringObj(interp, target_types[x]->name, -1));
4476         }
4477         return JIM_OK;
4478 }
4479
4480 static int jim_target_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4481 {
4482         if (argc != 1)
4483         {
4484                 Jim_WrongNumArgs(interp, 1, argv, "Too many parameters");
4485                 return JIM_ERR;
4486         }
4487         Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
4488         struct target *target = all_targets;
4489         while (target)
4490         {
4491                 Jim_ListAppendElement(interp, Jim_GetResult(interp),
4492                         Jim_NewStringObj(interp, target_name(target), -1));
4493                 target = target->next;
4494         }
4495         return JIM_OK;
4496 }
4497
4498 static int jim_target_create(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4499 {
4500         Jim_GetOptInfo goi;
4501         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4502         if (goi.argc < 3)
4503         {
4504                 Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv,
4505                         "<name> <target_type> [<target_options> ...]");
4506                 return JIM_ERR;
4507         }
4508         return target_create(&goi);
4509 }
4510
4511 static int jim_target_number(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4512 {
4513         Jim_GetOptInfo goi;
4514         Jim_GetOpt_Setup(&goi, interp, argc - 1, argv + 1);
4515
4516         /* It's OK to remove this mechanism sometime after August 2010 or so */
4517         LOG_WARNING("don't use numbers as target identifiers; use names");
4518         if (goi.argc != 1)
4519         {
4520                 Jim_SetResult_sprintf(goi.interp, "usage: target number <number>");
4521                 return JIM_ERR;
4522         }
4523         jim_wide w;
4524         int e = Jim_GetOpt_Wide(&goi, &w);
4525         if (e != JIM_OK)
4526                 return JIM_ERR;
4527
4528         struct target *target;
4529         for (target = all_targets; NULL != target; target = target->next)
4530         {
4531                 if (target->target_number != w)
4532                         continue;
4533
4534                 Jim_SetResultString(goi.interp, target_name(target), -1);
4535                 return JIM_OK;
4536         }
4537         Jim_SetResult_sprintf(goi.interp,
4538                         "Target: number %d does not exist", (int)(w));
4539         return JIM_ERR;
4540 }
4541
4542 static int jim_target_count(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4543 {
4544         if (argc != 1)
4545         {
4546                 Jim_WrongNumArgs(interp, 1, argv, "<no parameters>");
4547                 return JIM_ERR;
4548         }
4549         unsigned count = 0;
4550         struct target *target = all_targets;
4551         while (NULL != target)
4552         {
4553                 target = target->next;
4554                 count++;
4555         }
4556         Jim_SetResult(interp, Jim_NewIntObj(interp, count));
4557         return JIM_OK;
4558 }
4559
4560 static const struct command_registration target_subcommand_handlers[] = {
4561         {
4562                 .name = "create",
4563                 .mode = COMMAND_ANY,
4564                 .jim_handler = &jim_target_create,
4565                 .usage = "<name> <type> ...",
4566                 .help = "Returns the currently selected target",
4567         },
4568         {
4569                 .name = "current",
4570                 .mode = COMMAND_ANY,
4571                 .jim_handler = &jim_target_current,
4572                 .help = "Returns the currently selected target",
4573         },
4574         {
4575                 .name = "types",
4576                 .mode = COMMAND_ANY,
4577                 .jim_handler = &jim_target_types,
4578                 .help = "Returns the available target types as a list of strings",
4579         },
4580         {
4581                 .name = "names",
4582                 .mode = COMMAND_ANY,
4583                 .jim_handler = &jim_target_names,
4584                 .help = "Returns the names of all targets as a list of strings",
4585         },
4586         {
4587                 .name = "number",
4588                 .mode = COMMAND_ANY,
4589                 .jim_handler = &jim_target_number,
4590                 .usage = "<number>",
4591                 .help = "Returns the name of target <n>",
4592         },
4593         {
4594                 .name = "count",
4595                 .mode = COMMAND_ANY,
4596                 .jim_handler = &jim_target_count,
4597                 .help = "Returns the number of targets as an integer",
4598         },
4599         COMMAND_REGISTRATION_DONE
4600 };
4601
4602
4603 struct FastLoad
4604 {
4605         uint32_t address;
4606         uint8_t *data;
4607         int length;
4608
4609 };
4610
4611 static int fastload_num;
4612 static struct FastLoad *fastload;
4613
4614 static void free_fastload(void)
4615 {
4616         if (fastload != NULL)
4617         {
4618                 int i;
4619                 for (i = 0; i < fastload_num; i++)
4620                 {
4621                         if (fastload[i].data)
4622                                 free(fastload[i].data);
4623                 }
4624                 free(fastload);
4625                 fastload = NULL;
4626         }
4627 }
4628
4629
4630
4631
4632 COMMAND_HANDLER(handle_fast_load_image_command)
4633 {
4634         uint8_t *buffer;
4635         size_t buf_cnt;
4636         uint32_t image_size;
4637         uint32_t min_address = 0;
4638         uint32_t max_address = 0xffffffff;
4639         int i;
4640
4641         struct image image;
4642
4643         int retval = CALL_COMMAND_HANDLER(parse_load_image_command_CMD_ARGV,
4644                         &image, &min_address, &max_address);
4645         if (ERROR_OK != retval)
4646                 return retval;
4647
4648         struct duration bench;
4649         duration_start(&bench);
4650
4651         if (image_open(&image, CMD_ARGV[0], (CMD_ARGC >= 3) ? CMD_ARGV[2] : NULL) != ERROR_OK)
4652         {
4653                 return ERROR_OK;
4654         }
4655
4656         image_size = 0x0;
4657         retval = ERROR_OK;
4658         fastload_num = image.num_sections;
4659         fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4660         if (fastload == NULL)
4661         {
4662                 image_close(&image);
4663                 return ERROR_FAIL;
4664         }
4665         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4666         for (i = 0; i < image.num_sections; i++)
4667         {
4668                 buffer = malloc(image.sections[i].size);
4669                 if (buffer == NULL)
4670                 {
4671                         command_print(CMD_CTX, "error allocating buffer for section (%d bytes)",
4672                                                   (int)(image.sections[i].size));
4673                         break;
4674                 }
4675
4676                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4677                 {
4678                         free(buffer);
4679                         break;
4680                 }
4681
4682                 uint32_t offset = 0;
4683                 uint32_t length = buf_cnt;
4684
4685
4686                 /* DANGER!!! beware of unsigned comparision here!!! */
4687
4688                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4689                                 (image.sections[i].base_address < max_address))
4690                 {
4691                         if (image.sections[i].base_address < min_address)
4692                         {
4693                                 /* clip addresses below */
4694                                 offset += min_address-image.sections[i].base_address;
4695                                 length -= offset;
4696                         }
4697
4698                         if (image.sections[i].base_address + buf_cnt > max_address)
4699                         {
4700                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4701                         }
4702
4703                         fastload[i].address = image.sections[i].base_address + offset;
4704                         fastload[i].data = malloc(length);
4705                         if (fastload[i].data == NULL)
4706                         {
4707                                 free(buffer);
4708                                 break;
4709                         }
4710                         memcpy(fastload[i].data, buffer + offset, length);
4711                         fastload[i].length = length;
4712
4713                         image_size += length;
4714                         command_print(CMD_CTX, "%u bytes written at address 0x%8.8x",
4715                                                   (unsigned int)length,
4716                                                   ((unsigned int)(image.sections[i].base_address + offset)));
4717                 }
4718
4719                 free(buffer);
4720         }
4721
4722         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4723         {
4724                 command_print(CMD_CTX, "Loaded %" PRIu32 " bytes "
4725                                 "in %fs (%0.3f kb/s)", image_size, 
4726                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4727
4728                 command_print(CMD_CTX,
4729                                 "WARNING: image has not been loaded to target!"
4730                                 "You can issue a 'fast_load' to finish loading.");
4731         }
4732
4733         image_close(&image);
4734
4735         if (retval != ERROR_OK)
4736         {
4737                 free_fastload();
4738         }
4739
4740         return retval;
4741 }
4742
4743 COMMAND_HANDLER(handle_fast_load_command)
4744 {
4745         if (CMD_ARGC > 0)
4746                 return ERROR_COMMAND_SYNTAX_ERROR;
4747         if (fastload == NULL)
4748         {
4749                 LOG_ERROR("No image in memory");
4750                 return ERROR_FAIL;
4751         }
4752         int i;
4753         int ms = timeval_ms();
4754         int size = 0;
4755         int retval = ERROR_OK;
4756         for (i = 0; i < fastload_num;i++)
4757         {
4758                 struct target *target = get_current_target(CMD_CTX);
4759                 command_print(CMD_CTX, "Write to 0x%08x, length 0x%08x",
4760                                           (unsigned int)(fastload[i].address),
4761                                           (unsigned int)(fastload[i].length));
4762                 if (retval == ERROR_OK)
4763                 {
4764                         retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4765                 }
4766                 size += fastload[i].length;
4767         }
4768         int after = timeval_ms();
4769         command_print(CMD_CTX, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4770         return retval;
4771 }
4772
4773 static const struct command_registration target_command_handlers[] = {
4774         {
4775                 .name = "targets",
4776                 .handler = &handle_targets_command,
4777                 .mode = COMMAND_ANY,
4778                 .help = "change current command line target (one parameter) "
4779                         "or list targets (no parameters)",
4780                 .usage = "[<new_current_target>]",
4781         },
4782         {
4783                 .name = "target",
4784                 .mode = COMMAND_CONFIG,
4785                 .help = "configure target",
4786
4787                 .chain = target_subcommand_handlers,
4788         },
4789         COMMAND_REGISTRATION_DONE
4790 };
4791
4792 int target_register_commands(struct command_context *cmd_ctx)
4793 {
4794         return register_commands(cmd_ctx, NULL, target_command_handlers);
4795 }
4796
4797 static const struct command_registration target_exec_command_handlers[] = {
4798         {
4799                 .name = "fast_load_image",
4800                 .handler = &handle_fast_load_image_command,
4801                 .mode = COMMAND_ANY,
4802                 .help = "Load image into memory, mainly for profiling purposes",
4803                 .usage = "<file> <address> ['bin'|'ihex'|'elf'|'s19'] "
4804                         "[min_address] [max_length]",
4805         },
4806         {
4807                 .name = "fast_load",
4808                 .handler = &handle_fast_load_command,
4809                 .mode = COMMAND_ANY,
4810                 .help = "loads active fast load image to current target "
4811                         "- mainly for profiling purposes",
4812         },
4813         {
4814                 .name = "profile",
4815                 .handler = &handle_profile_command,
4816                 .mode = COMMAND_EXEC,
4817                 .help = "profiling samples the CPU PC",
4818         },
4819         /** @todo don't register virt2phys() unless target supports it */
4820         {
4821                 .name = "virt2phys",
4822                 .handler = &handle_virt2phys_command,
4823                 .mode = COMMAND_ANY,
4824                 .help = "translate a virtual address into a physical address",
4825         },
4826
4827         {
4828                 .name = "reg",
4829                 .handler = &handle_reg_command,
4830                 .mode = COMMAND_EXEC,
4831                 .help = "display or set a register",
4832         },
4833
4834         {
4835                 .name = "poll",
4836                 .handler = &handle_poll_command,
4837                 .mode = COMMAND_EXEC,
4838                 .help = "poll target state",
4839         },
4840         {
4841                 .name = "wait_halt",
4842                 .handler = &handle_wait_halt_command,
4843                 .mode = COMMAND_EXEC,
4844                 .help = "wait for target halt",
4845                 .usage = "[time (s)]",
4846         },
4847         {
4848                 .name = "halt",
4849                 .handler = &handle_halt_command,
4850                 .mode = COMMAND_EXEC,
4851                 .help = "halt target",
4852         },
4853         {
4854                 .name = "resume",
4855                 .handler = &handle_resume_command,
4856                 .mode = COMMAND_EXEC,
4857                 .help = "resume target",
4858                 .usage = "[<address>]",
4859         },
4860         {
4861                 .name = "reset",
4862                 .handler = &handle_reset_command,
4863                 .mode = COMMAND_EXEC,
4864                 .usage = "[run|halt|init]",
4865                 .help = "Reset all targets into the specified mode."
4866                         "Default reset mode is run, if not given.",
4867         },
4868         {
4869                 .name = "soft_reset_halt",
4870                 .handler = &handle_soft_reset_halt_command,
4871                 .mode = COMMAND_EXEC,
4872                 .help = "halt the target and do a soft reset",
4873         },
4874         {
4875
4876                 .name = "step",
4877                 .handler = &handle_step_command,
4878                 .mode = COMMAND_EXEC,
4879                 .help = "step one instruction from current PC or [addr]",
4880                 .usage = "[<address>]",
4881         },
4882         {
4883
4884                 .name = "mdw",
4885                 .handler = &handle_md_command,
4886                 .mode = COMMAND_EXEC,
4887                 .help = "display memory words",
4888                 .usage = "[phys] <addr> [count]",
4889         },
4890         {
4891                 .name = "mdh",
4892                 .handler = &handle_md_command,
4893                 .mode = COMMAND_EXEC,
4894                 .help = "display memory half-words",
4895                 .usage = "[phys] <addr> [count]",
4896         },
4897         {
4898                 .name = "mdb",
4899                 .handler = &handle_md_command,
4900                 .mode = COMMAND_EXEC,
4901                 .help = "display memory bytes",
4902                 .usage = "[phys] <addr> [count]",
4903         },
4904         {
4905
4906                 .name = "mww",
4907                 .handler = &handle_mw_command,
4908                 .mode = COMMAND_EXEC,
4909                 .help = "write memory word",
4910                 .usage = "[phys]  <addr> <value> [count]",
4911         },
4912         {
4913                 .name = "mwh",
4914                 .handler = &handle_mw_command,
4915                 .mode = COMMAND_EXEC,
4916                 .help = "write memory half-word",
4917                 .usage = "[phys] <addr> <value> [count]",
4918         },
4919         {
4920                 .name = "mwb",
4921                 .handler = &handle_mw_command,
4922                 .mode = COMMAND_EXEC,
4923                 .help = "write memory byte",
4924                 .usage = "[phys] <addr> <value> [count]",
4925         },
4926         {
4927
4928                 .name = "bp",
4929                 .handler = &handle_bp_command,
4930                 .mode = COMMAND_EXEC,
4931                 .help = "list or set breakpoint",
4932                 .usage = "[<address> <length> [hw]]",
4933         },
4934         {
4935                 .name = "rbp",
4936                 .handler = &handle_rbp_command,
4937                 .mode = COMMAND_EXEC,
4938                 .help = "remove breakpoint",
4939                 .usage = "<address>",
4940         },
4941         {
4942
4943                 .name = "wp",
4944                 .handler = &handle_wp_command,
4945                 .mode = COMMAND_EXEC,
4946                 .help = "list or set watchpoint",
4947                 .usage = "[<address> <length> <r/w/a> [value] [mask]]",
4948         },
4949         {
4950                 .name = "rwp",
4951                 .handler = &handle_rwp_command,
4952                 .mode = COMMAND_EXEC,
4953                 .help = "remove watchpoint",
4954                 .usage = "<address>",
4955
4956         },
4957         {
4958                 .name = "load_image",
4959                 .handler = &handle_load_image_command,
4960                 .mode = COMMAND_EXEC,
4961                 .usage = "<file> <address> ['bin'|'ihex'|'elf'|'s19'] "
4962                         "[min_address] [max_length]",
4963         },
4964         {
4965                 .name = "dump_image",
4966                 .handler = &handle_dump_image_command,
4967                 .mode = COMMAND_EXEC,
4968                 .usage = "<file> <address> <size>",
4969         },
4970         {
4971                 .name = "verify_image",
4972                 .handler = &handle_verify_image_command,
4973                 .mode = COMMAND_EXEC,
4974                 .usage = "<file> [offset] [type]",
4975         },
4976         {
4977                 .name = "test_image",
4978                 .handler = &handle_test_image_command,
4979                 .mode = COMMAND_EXEC,
4980                 .usage = "<file> [offset] [type]",
4981         },
4982         {
4983                 .name = "ocd_mem2array",
4984                 .mode = COMMAND_EXEC,
4985                 .jim_handler = &jim_mem2array,
4986                 .help = "read memory and return as a TCL array "
4987                         "for script processing",
4988                 .usage = "<arrayname> <width=32|16|8> <address> <count>",
4989         },
4990         {
4991                 .name = "ocd_array2mem",
4992                 .mode = COMMAND_EXEC,
4993                 .jim_handler = &jim_array2mem,
4994                 .help = "convert a TCL array to memory locations "
4995                         "and write the values",
4996                 .usage = "<arrayname> <width=32|16|8> <address> <count>",
4997         },
4998         COMMAND_REGISTRATION_DONE
4999 };
5000 int target_register_user_commands(struct command_context *cmd_ctx)
5001 {
5002         int retval = ERROR_OK;
5003         if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
5004                 return retval;
5005
5006         if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
5007                 return retval;
5008
5009
5010         return register_commands(cmd_ctx, NULL, target_exec_command_handlers);
5011 }