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