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