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