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